从函数返回期间未调用复制构造函数
copy constructor not called during return from a function
为什么在主函数的最后一行中没有为函数 func 的返回调用调用调用复制构造函数。当我按值发送参数时调用它,但在返回值时不调用它
class A
{
public:
int x , y , z;
A(int x=4 , int y=2 , int z=1)
{
this->x = x;
this->y = y;
this->z = z;
}
A(A& a)
{
x = a.x;
y = a.y;
z = a.z;
printf("Copy Constructor calledn");
a.x++;
}
//not a copy constructor
A(A *a)
{
x = a->x;
y = a->y;
z = a->z;
printf("Some Constructor calledn");
(a->x)++;
}
void tell() { printf("x=%d y=%d z=%dn" , x , y , z);}
};
A func()
{
A a;
return a;
}
int main()
{
A a1;
a1=func(); //why is copy constructor not called while returning
a1.tell();
return 0;
}
这是因为复制省略。允许编译器省略副本并将结果直接存储在对象中。您可以使用编译器选项-fno-elide-constructors
关闭复制 elision(不过我不建议这样做)。
相关:什么是复制省略和返回值优化?
相关文章:
- 当从函数参数中的临时值调用复制构造函数时
- 为什么调用复制构造函数而不是移动构造函数?
- 为用户定义的类正确调用复制构造函数/赋值运算符
- 编译器调用复制运算符而不是移动运算符
- push_back std::vector,则重复调用复制构造函数
- 为什么调用复制构造函数来构造空unique_ptr向量?
- 为什么转换运算符调用复制构造函数两次,而等效函数只调用它一次
- 我打算调用initializer_list构造函数,如果存在,则事先调用复制构造函数:为什么?
- C++ - 从移动分配运算符调用复制分配
- 构造函数初始值设定项列表未调用复制构造函数
- 为什么在我的代码中调用复制构造函数而不是移动构造函数?
- std::map 在 [] 上调用默认构造函数,在 insert() 上调用复制构造函数
- 通过引用传递对象时是否调用复制构造函数?
- 如果函数按值传递并按值返回,将调用复制构造函数多少次
- 为什么要抛出引用调用复制构造函数的异常?
- 为什么即使参数标记为"const",也会调用复制构造函数?
- Clang-Tidy:移动构造函数通过调用复制构造函数来初始化类成员
- 为什么当我添加一个不同的对象(复制构造函数中的参数)时调用复制构造函数?
- 为什么调用复制构造函数,当我只返回对象 c++ 的引用时
- 为什么在下面的代码中调用复制构造函数两次