You must create your own copy constructor and assignment operator (and usually default constructor too) when:
- You want your object to be copied or assigned, or put into a standard container such as
vector
- The default copy constructor and assignment operator will not do the Right Thing.
Consider the following code:
class A; // defined elsewhere
class B {
private:
A *my_very_own_a;
};
If you let the automatic copy constructor copy a B
, it will copy the A *
pointer value across, so that the copy points to the same A
instance as the original. But part of the design of this class is that each B
has its own A
, so the automatic copy constructor has broken that contract. So you need to write your own copy constructor which will create a new A
for the new B
to point to.
However, consider this case:
class A; // defined elsewhere
class B {
private:
A *shared_reference_to_a;
};
Here each B
contains a pointer to an A
, but the class contract doesn't demand a unique A
for each B
. So the automatic copy constructor might well do the Right Thing here.
Note that both examples are the same code, but with different design intent.
An example of the first situation might be B
== dialog box, A
== button. If you create a copy of a dialog box, it probably needs a copy of all the contents too.
An example of the second might be B
== dialog box, A
== reference to window manager. If you copy a dialog box, the copy probably exists in the same window manager as the original.