简体   繁体   中英

Why copy constructor is generated if there is a destructor

With high risk of duplicate,

In C++, if you have custom destructor, you probably need to write own copy constructor and copy assignment operator.

In C++11 you also probably need to do move constructor and move assignment operator.

Why compiler auto-generates all these methods, if there is a custom destructor?

Note:

Question does not ask what are conditions of auto-generating all these methods.

Question is why is decided those methods to be auto-generated even d-tor is added.

I can post several examples of broken code because of generating those methods, such this one:

class FileDescriptorGuard{
    int fd;

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

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

Here disaster will happen when object is copied or moved.

After I did some research with lots of help from Sergey Zubkov, it seems "Praetorian" give part of the answer.

In C++11 , copy c-tors are generated for backwards compatibility.

Move c-tors are NOT generated, because this is feature introduced in C++11 .

However, if you are using clang with -Wdeprecated , a warning is issued. Here is an example program:

class FileDescriptorGuard;

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

Here is the compiler output:

$ 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.

If you are using gcc , there is no such warning.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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