The rule of three (also known as the Law of The Big Three or The Big Three) is a rule of thumb in C++ that claims that if a class defines one of the following it should probably explicitly define all three: destructor, copy constructor, copy assignment operator.
Why is a non-default constructor not considered as one of them? When there is any resource managed in the class, programmer has to define a non-default constructor anyway.
Why is a non-default constructor not considered as one of them? When there is any resource managed in the class, programmer has to define a non-default constructor anyway.
That is not necessarily true. The constructor might not aquire any resource. Other function(s) might aquire them as well. In fact, there can be many functions (including the constructor(s) themselves) which might aquire resources. For example, in case of std::vector<T>
, it is resize()
and reserve()
which aquire resources. So think of constructor(s) just like other function(s) which might aquire resources.
The idea of this rule is that when you make a copy, the default-copy code generated by the compiler wouldn't work. Hence you need to write the copy-semantic yourself. And since the class manages resources (it doesn't matter which function(s) aquire it), the destructor must release it, because the destructor is guaranteed to be executed, for a fully constructed object. Hence you've to define the destructor as well. And in C++11, you've to implement move-semantics as well. The logical argument for move-semantic is same as that of copy-semantics, except that in move semantic, you changed the source as well. Move-semantic is much like organ-donor; when you give your organ to other, you don't own it anymore.