簡體   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