The Rule of Three:
The rule of three in c++ is that three member functions will go together: the destructor, the copy constructor, and the assignment operator. A class that defines any of the above three methods should almost always define the other two members.
The Rule of Three is really two rules:
- If a class has a nonempty destructor, it almost always needs a copy constructor and an assignment operator.
- If a class has a nontrivial copy constructor or assignment operator, it usually needs both of these members and a destructor as well.
Rule of Thumb:
- Initialization of the pointer in each of the constructors. If no memory is to be allocated to the pointer in a particular constructor, the pointer should be initialized to 0 (i.e., the null pointer).
- Deletion of the existing memory and assignment of new memory in the assignment operator.
- Deletion of the pointer in the destructor. (certainly don't delete on a pointer that wasn't initialized via new, and, except in the case of smart pointer objects)