Nick
Nick

Reputation: 10539

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.

Upvotes: 1

Views: 1119

Answers (1)

Nick
Nick

Reputation: 10539

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.

Upvotes: 4

Related Questions