Cloning (programming)
In computer science, cloning refers to the making of an exact copy of an object, frequently under the paradigm of instance-based programming, or object-oriented programming (OOP). Shallow copiesIn most programming languages (exceptions include Ruby), primitive types such as Copying primitive types in Java or C++: int original = 42;
int copy = 0;
copy = original;
Many OOP programming languages (including Java, D, ECMAScript, and C#) make use of object references. Object references, which are similar to pointers in other languages, allow for objects to be passed around by address so that the whole object need not be copied. A Java example, when "copying" an object using simple assignment: Object original = new Object();
Object copy = null;
copy = original; // does not copy object but only its reference
The object is not duplicated, the variables 'original' and 'copy' are actually referring to the same object. In C++, the equivalent code Object* original = new Object();
Object* copy = NULL;
copy = original;
makes it clear that it is a pointer to the object being copied, not the object itself. CloningThe process of actually making another exact replica of the object instead of just its reference is called cloning. In most languages, the language or libraries can facilitate some sort of cloning. In Java, the Cloning an object in Java: Object originalObj = new Object();
Object copyObj = null;
copyObj = originalObj.clone(); // duplicates the object and assigns the new reference to 'copyObj'
→ C++ objects in general behave like primitive types, so to copy a C++ object one could use the ' A C++ example of object cloning: Object originalObj;
Object copyObj(originalObj); // creates a copy of originalObj named copyObj
A C++ example of object cloning using pointers (to avoid slicing see[1]): Object* originalObj = new Object;
Object* copyObj = nullptr;
copyObj = new Object(*originalObj); // creates a copy of originalObj and assigns its address to copyObj
References
|
Portal di Ensiklopedia Dunia