Monday, May 19, 2014

Rule Of Three (Gang of Three)

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:

  1. If a class has a nonempty destructor, it almost always needs a copy constructor and an assignment operator.
  2. 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:

  1. 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).
  2. Deletion of the existing memory and assignment of new memory in the assignment operator.
  3. 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)

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home