Why isn’t memcpy guaranteed to be safe for non-POD types?

Try bit-wise copying std::shared_ptr<>. You might find that your program blows up in your face more often than not.

You’ll encounter this problem with any class whose copy constructor does something other than a bit-wise copy. In the case of std::shared_ptr<>, it’ll copy the pointer but won’t increment the reference count, so you’ll end up freeing the shared object and its reference count early, and then blowing up when the copied shared_ptr tries to decrement the freed reference count.


UPDATE: It was pointed out that this doesn’t quite answer the question, which is fair, since I mainly addressed the idea of copying shared_ptr to shared_ptr, not shared_ptr to char[] and back again. However, the principle still holds.

If you bit-wise copy a shared_ptr to a char[], assign a different value to the shared_ptr, then copy the char[] back over, the end result may be to leak one object and double-delete another, i.e., UB.

The same might happen with a POD, but that would be a bug in the program logic. Bit-wise copying back into the POD equivalent of a modified shared_ptr would be perfectly valid as long as the program understands and accommodates such an event. Doing so for a std::shared_ptr generally won’t work.

Leave a Comment