繁体   English   中英

如果存在析构函数,为什么会生成复制构造函数

[英]Why copy constructor is generated if there is a destructor

重复的风险很高,

在C ++中,如果您具有自定义析构函数,则可能需要编写自己的副本构造函数和副本赋值运算符。

在C ++ 11中,您可能还需要执行移动构造函数和移动赋值运算符。

如果有自定义析构函数,为什么编译器会自动生成所有这些方法?

注意:

问题不问自动生成所有这些方法的条件是什么。

问题是为什么决定添加d-tor也会自动生成那些方法。

由于生成了这些方法,因此我可以发布几个破坏代码的示例,例如:

class FileDescriptorGuard{
    int fd;

public:
    FileDescriptorGuard(int const fd) : fd(fd){}

    ~FileDescriptorGuard(){
        ::close(fd);
    }
};

复制或移动对象时会发生灾难。

在谢尔盖·祖布科夫(Sergey Zubkov)的大力帮助下进行了一些研究之后,似乎“普雷托里亚语”给出了部分答案。

C++11 ,生成了copy c-tors以实现向后兼容。

不会生成Move c-tors ,因为这是C++11引入的功能。

但是,如果将clang-Wdeprecated一起使用,则会发出警告。 这是一个示例程序:

class FileDescriptorGuard;

int main(){
    FileDescriptorGuard x(5);
    FileDescriptorGuard y = x;
}

这是编译器的输出:

$ clang -Wdeprecated -std=c++11  x.cc -lstdc++ 
x.cc:9:5: warning: definition of implicit copy constructor for 'FileDescriptorGuard' is deprecated because it has a user-declared
      destructor [-Wdeprecated]
    ~FileDescriptorGuard(){
    ^
x.cc:16:26: note: implicit copy constructor for 'FileDescriptorGuard' first required here
        FileDescriptorGuard y = x;
                                ^
1 warning generated.

如果您使用的是gcc ,则不会出现此类警告。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM