Trent Boult
Trent Boult

Reputation: 117

Is this the correct logic behind the rule of three?

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?

Upvotes: 1

Views: 83

Answers (1)

vsoftco
vsoftco

Reputation: 56577

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.

Upvotes: 2

Related Questions