Difference between shallow copy (default) and deep copy of objects

When using “=” operator coping an object, the default or so-called shallow copy will be executed.

In java, shallow copy is like another name for the object(like the reference or pointer in C++), expect the basic data types, both objects at each side of “=” operator will be pointed to the same piece of memory.

In C++, shallow copy will cause a “=” operation from all the members of the first objects to the members in the second object, including those pointers. Thus deleting the second object might cause the destructor to release the pointers in the first object and further more cause troubles.

For deep copy, it is actually a function or method that allows developer themselves to define what to do during a copy.

For Java, a clone method from class Object can be override for cloning an object: Object clone(); To call it, a new instance shall be returned.

For C++, a constructor will the parameter of a reference of the class is used for the copy constructor:


class T{
public:
T(T &t);
};

Use T tCopy(tOriginal); to deep copy an object.

2017/3/20