When creating a value object, it is therefore essential that you follow the rule of “
The Big Three.”
This term was introduced by Marshall Cline in the early nineties and essentially states that there are three member functions that always go together: the
destructor, the
copy constructor, and the
assignment operator .
If you define one of these, you normally need to define the other two as well.
(Note: Declaring an
empty virtual destructor to enable subclassing is one exception, as it does not perform any actual deallocation).
Copy constructor.
A copy constructor is a special constructor that creates a new object from an existing object. If you do not define a copy constructor, the compiler will generate one for you that performs a shallow copy of the existing object's member variables. So if your object allocates any resources, you most likely need a copy constructor so that you can perform a deep
copy.
The copy constructor gets called in the following situations:
• An object is passed to a method by value or returned by value
• An object is initialized using the syntax, MyClass a = b;
• An object is placed in a brace-enclosed initializer list
• An object is thrown or caught in an exception
Assignment operator.
The assignment operator is used to assign the value of one object to another object, for example, a = b. It differs from the copy constructor in that the object being assigned to already exists.
Some guidelines for implementing the assignment operator include:
1. Use a const reference for the right-hand operand.
2. Return *this as a reference to allow operator chaining.
3. Destroy any existing state before setting the new state.
4. Check for self-assignment (a = a) by comparing this to &rhs.
Destructor.
The destructor is called in response to a delete call in order to release any resources that the object is holding. There can be only one destructor for a class. If you do not specify a destructor, your C++ compiler will generate one automatically.
The compiler will also generate code to automatically call the destructors for all of your member variables, in the reverse order they appear in the class declaration.
Tips 1:
If your class allocates resources, you should follow the rule of The Big Three and define a destructor, copy
constructor, and assignment operator.
Tips 2:
To prevent copies, a class must explicitly declare its copy constructor as private or use boost::noncopyable.
Tip 3:
Always prefer passing a non-mutable object as a const reference rather than passing it by value. This will avoid the memory and performance costs to create and destroy a temporary copy of the object and all of its member and inherited objects.