1

If we define our very own destructor, it means that there is some dynamically allocated variable. And therefore, we need to define the copy constructor and copy assignment operator as well because we definitely are dealing with a pointer somewhere.

Is this the main logic behind the rule?

  • Not necessarily a pointer, just any resource that needs cleaning up but which is not correctly copied by the default-generated copy constructor. – M.M Mar 11 '15 at 23:25

1 Answers1

2

Pretty much. In C++11 this becomes the rule of five, as move semantics is disabled by declaring a destructor or copy constructor/assignment operator. But it is better to follow the rule of zero, i.e. use RAII to perform automatic release of resources via smart pointers etc.

Note that you may not need to deal with a pointer directly to need a custom destructor, but with a resource that is not managed via RAII, e.g. a file open via fopen for which you have to call fclose, or some connection to a database etc. So the rule is to use RAII so that destructors take care of the resources that are acquired.

Community
  • 1
  • 1
vsoftco
  • 52,188
  • 7
  • 109
  • 221
  • 1
    @TrentBoult this indeed is extremely unfortunate, as new generations of programmers write C++ code in C style... – vsoftco Mar 11 '15 at 21:25
  • 1
    I'm frankly not sure whether to upvote or flag your comment. I ultimately had to settle for both. Well played good sir. – Puppy Mar 11 '15 at 21:26