Search

The Online Encyclopedia and Dictionary

 
     
 

Encyclopedia

Dictionary

Quotes

 

Duplication

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

Last updated: 05-28-2005 20:38:19
The contents of this article are licensed from Wikipedia.org under the GNU Free Documentation License. How to see transparent copy