C++ bitwise vs memberwise copying? [closed]

2019-05-13 22:04发布

问题:

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?

回答1:

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.



回答2:

  • 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.)



回答3:

If you are binary copying an object then there may be internals such as reference counters that should not be copied. A bitwise copy would break this. A member copy will use the correct functions.



回答4:

You might get in trouble when bitwise copying reference or pointer type members. Depends on what you really need and can handle by means of having a shallow or deep copy for the resulting class instance.