分类: C/C++
2009-09-23 22:08:50
class A
{
string s;
};
A a;
A b;
a=b; //deep copy
When assigning b to a, the compiler-generated assignment operator of
class A first invokes the assignment operator of class std::string.
Thus, a.s and b.s are well-defined, and they are probably not
binary-identical. On the other hand, a shallow copy (also called
"bitwise copy") simply copies chunks of memory from one location to
another. A memcpy() operation is an example of a shallow copy. Because
memcpy() does not respect object semantics, it will not invoke the copy
constructor of an object. Therefore, you should never use memcpy() to
copy objects. Use it only when copying POD (Plain Old Data) types:
ints, floating point numbers, and dumb structs.
--------------------------------------------------------------------
~lukes/TEXTBOOK/notes-cpp/oop-condestructors/shallowdeepcopy.html
A shallow copy of an object copies all of the member field values. This works well if the fields are values, but may not be what you want for fields that point to dynamically allocated memory. The pointer will be copied. but the memory it points to will not be copied -- the field in both the original object and the copy will then point to the same dynamically allocated memory, which is not usually what you want. The default copy constructor and assignment operator make shallow copies.
A deep copy copies all fields, and makes copies of dynamically allocated memory pointed to by the fields. To make a deep copy, you must write a copy constructor and overload the assignment operator, otherwise the copy will point to the original, with disasterous consequences.