Object copy
|
In computing, a deep copy is copy that contains the complete encapsulated data of the original object, allowing it to be used independently of the original object. In contrast, a shallow copy is a copy that may be associated to data shared by the original and the copy.
For example, if a C++ class contains a pointer to a null-terminated string, the deep copy would also copy the string, while the shallow copy would create an object where the pointer points to same string, and changes to it affect both objects.
In computing, the result of shallow copying one object to another variable is two variables pointing to the same physical object in memory.
Thus changing the object pointed to by one of the variables will also cause the contents of the other variable to change (since the same object in memory is being altered).
Shallow copies are common when reference counting objects. The technique is by default when copying objects in Java.
In computer science, duplication of data or objects involves copying data byte by byte and, if needed, changing metadata about objects.
Duplication of data
In C, one can use memmove or memcopy to copy data on the memory.
Duplication of objects
A built-in method called a copy constructor can be used to easily duplicate most objects. Programmers typically implement the copy constructor as a recursive copy of all attributes and of all objects belonging to the object, one-by-one. This can take a lot of time. The duplication of lists, for instance, involves copying each element.
Implementors may set up some copy constructors with reference counting so that identical copies of an object do not take up additional memory. This technique interacts badly with low-level access to internal object data. Defensive copy is an act to ensure that the object retains a state that exists at the moment of duplication. Code here (http://www.sgi.com/tech/stl/string_discussion.html) addresses an interesting problem which relates to the implementation of string class in the STL:
#include <iostream> #include <string> using namespace std; int main() { string s("abc"); string t; char & c(s[1]); t = s; // Data typically shared between s and t. c = 'z'; // How many strings does this modify? if (t[1] == 'z') cout << "wrong" << endl; else cout << "right" << endl; }
The specification of C++ understandably frowns on changing t
. One can only mitigate this problem by the use of defensive copy, but this in turn wipes out any benefit gained by the use of reference counting.