views:

189

answers:

3

Duplicate of this.

In C++ you sometimes have to implement the copy constructor yourself (when you have pointer as a member usually). Over compiler generated copy constructor this has the disadvantage that when you add a member field and forget to add the copying line in the copy constructor, you have a problem, which is often hard to track down. I like to program defensively and this worries me a bit.

One solution would be to use memcpy and then just handle the pointers properly, but this is discouraged as I understand it.

A: 

No, do not use memcpy. You run the risk of overwriting data that you don't even know exists (vtables, for example.) Also, if the field that you've added is itself a pointer, then you haven't solved anything.

The best practices for programming defensively for this situation are:

  • Be in the habit of examining your class constructors, destructors, etc. whenever you add fields

  • Have automated tests

  • Use memory debugging tools such as Purify (open-source tools are also available that may help.)

Dan Breslau
+1  A: 

Don't do it - it won't work either way if someone adds a pointer member variable and forgets about the copy constructor - I'd suggest you add a compile time assert link text in the copy constuctor for the sizeof of your class - if the sizeof will change - the compile assert will fail and the code will not compile untill someone changes the condition - the possibility of someone changing the condition that sits next to a comment about making sure to copy all members correctly and not doing that is quite low ;)

RnR
This can cause problems if any of the fields are themselves class instances (not pointers), and the definitions of those classes are modified.
Dan Breslau
It'll only fire the compile-time assertion. Then it's time to reexamine: why did the size change? Does the added/changed member need a 'manual copy' addition? This technique has proved quite useful at my job; even though it sometimes triggers falsely.
xtofl
@Dan - you're right - this compilcates things but you still could calculate the "desired" size - all in all though I recoment Dan's idea after noting my comment :)
RnR
I meant Neil's :)
RnR
+2  A: 

Don't use naked pointers - use a smart pointer that will do the copy for you, if needed. Yo then no longer need to write a copy constructor - I have only written a single one in the past five years.

anon
This is nice - just make sure you have a smart pointer that will copy the object it points to and not just point to the same object as the original.
RnR