c++ - C++ 拷贝构造函数中的 const

标签 c++ copy copy-constructor

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/

相关文章:

java - 如果输入参数无效,如何在构造函数中制作防御性副本

audio - 使用 ffmpeg 从 28 分钟的视频中复制 5 秒

excel - VBA Excel 将文本文件复制到工作表

C++自定义类String赋值给C风格的String

c++ - 构造函数无法重新声明。为什么?

c++ - Xcode 6.1.1 是 C++ 的 ISO 标准吗?

c++ - 对头文件的混淆

具有不同参数的 C++ 多个构造函数

c++ - 如果类的成员是引用,为什么复制对象是非法的?

c++ - "attempting to reference a deleted function"用于复制构造函数