I am reading effective C++ in Item 5, it mentioned two cases in which I must define the copy assignment operator myself. The case is a class which contain const and reference members.
I am writing to ask what’s the general rule or case in which I must define my own copy constructor and assignment operator?
I would also like to know when I must define my own constructor and destructor.
Thanks so much!
You must create your own copy constructor and assignment operator (and usually default constructor too) when:
vectorConsider the following code:
If you let the automatic copy constructor copy a
B, it will copy theA *pointer value across, so that the copy points to the sameAinstance as the original. But part of the design of this class is that eachBhas its ownA, so the automatic copy constructor has broken that contract. So you need to write your own copy constructor which will create a newAfor the newBto point to.However, consider this case:
Here each
Bcontains a pointer to anA, but the class contract doesn’t demand a uniqueAfor eachB. 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.