class x
{
int a;
public:
x()
{
cout<<"\n\ndefault constructor";
}
x(x& obj)
{
cout<<"\n\ncopy constructor";
}
x fun()
{
x ob;
return ob;
}
};
int main()
{
x ob1;
x ob2=ob1.fun();
return 0;
}
最初,这段代码给出了一个错误“没有匹配函数来调用‘x::x(x)’”, 当我将复制构造函数更改为
x(const x& obj)
{
cout<<"\n\ncopy constructor";
}
输出变成
默认构造函数
默认构造函数
复制构造函数仍然没有执行....为什么?
最佳答案
这称为编译器完成的复制省略,这是语言规范所允许的。
查看此 wiki 条目:
至于为什么非常量版本给出编译错误,因为 obj1.fun()
返回一个不能绑定(bind)到非常量引用的临时对象,但它可以绑定(bind)到常量引用,所以const 版本编译正常。一旦将其设为常量引用,它仅用于语义检查,但编译器会优化代码,从而消除对复制构造函数的调用。
但是,如果您在 GCC 中使用 -fno-elide-constructors
选项编译它,则不会执行复制省略,而是调用复制构造函数。 GCC doc说,
-fno-elide-constructors
The C++ standard allows an implementation to omit creating a temporary which is only used to initialize another object of the same type. Specifying this option disables that optimization, and forces G++ to call the copy constructor in all cases.
关于c++ - C++ 拷贝构造函数中的 const,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8124322/