0

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.

Community
  • 1
  • 1
Roman Plášil
  • 1,941
  • 2
  • 17
  • 27

3 Answers3

2

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.

  • 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 Mar 27 '09 at 20:39
1

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
  • 2,096
  • 1
  • 15
  • 23
  • 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 Mar 27 '09 at 20:35
  • 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 Mar 27 '09 at 20:41
  • @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 Mar 27 '09 at 20:41
0

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
  • 11,472
  • 2
  • 35
  • 44