为什么在main函数的最后几行没有为函数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 called\n");
a.x++;
}
//not a copy constructor
A(A *a)
{
x = a->x;
y = a->y;
z = a->z;
printf("Some Constructor called\n");
(a->x)++;
}
void tell() { printf("x=%d y=%d z=%d\n" , 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;
}
答案 0 :(得分:1)
这是因为copy-elision。允许编译器省略副本并将结果直接存储在对象中。您可以使用编译器选项 -fno-elide-constructors
关闭copy-elision(我不建议这样做)。