FAQ 30.15 Why does copying an object using memcpy() cause a program crash?

FAQ 30.15 Why does copying an object using memcpy() cause a program crash?

Because bitwise copying is evil.

A class's copy operations (copy constructor and assignment operator) are supposed to copy the logical state of an object. In some cases, the logical state of an object can be copied using a bitwise copy (e.g., using memcpy()). However a bitwise copy doesn't make sense for a lot of objects; it may even put the copy in an incoherent state.

If a class X has a nontrivial copy constructor or assignment operator, bitwise copying an X object often creates wild pointers. One common case where bitwise copying of an object creates wild pointers is when the object owns a referent (that is, it has remote ownership). The wild pointers are a result of the bitwise copy operation, not some failure on the part of the class designer.

For example, consider a class that has remote ownership, such as a string class that allocates an array of char from the heap. If string object a is bitwise copied into string b, then the two objects both point to the same allocated array. One of these strings will die first, which will delete the allocated array owned by both of them. BOOM!

 #include <string> using namespace std; int main() {   string a = "fred";   string b;   #if 1     // Good: let the object copy itself:     b = a;   #else     // Bad: manipulate the object's bits:     memcpy(&b, &a, sizeof(string));   #endif } 

Note that a bitwise copy is safe if the object's exact class is known and the object is (and will always remain!) bitwise copyable. For example, class string might use memcpy() to copy its string data because char is and will always remain bitwise copyable (assuming that the string data is a simple array of char).



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net