Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ bitwise vs memberwise copying? [closed]

What is the difference between bitwise and memberwise copying? Surely if you copy the members then you will end up copying the bits representing the members anyway?

like image 752
user997112 Avatar asked Feb 27 '13 22:02

user997112


2 Answers

class MyClass
{
public:
    MyClass () : m_p (new int (5)) {}
    ~MyClass () {delete m_p;}
    int* m_p;
};

MyClass a;
MyClass b;
memcpy (&a, &b, sizeof (a));

I just leaked the allocated int in 'a' by rewriting it's member variable without freeing it first. And now 'a' and 'b' have an m_p that is pointing to the same memory location and both will delete that address on destruction. The second attempt to delete that memory will crash.

like image 80
cppguy Avatar answered Oct 23 '22 19:10

cppguy


  • Bitwise copying: copy the object representation of an object as an uninterpreted sequence of bytes.
  • Memberwise copying: copy each subobject of an object as appropriate for its type. For objects with a non-trivial copy constructor that means to invoke the copy constructor. For subobjects of trivially copyable type, that means bitwise copy.

Both are the same, so that the entire object is trivially copyable, if all subobjects are trivially copyable. (Class (sub)objects also must not have virtual member functions or virtual base classes.)

like image 21
JoergB Avatar answered Oct 23 '22 20:10

JoergB