DESCRIPTION c ++ and Java in shallow and deep copy copy

In Java clone mode is shallow copy, if you want to implement a deep copy, need to inherit clonable interfaces, override the clone method.

Shallow copy : the use of a known instance of a member of the newly created instance variable assignment one by one, this way is called a shallow copy.

Deep copy : When the copy constructor of a class, not only to copy the object reference variable value of all non-members, but also to create a new instance as a member variable of a reference type, and instance initialization value for the parameter form. This is called a deep copy.

That is only a shallow copy copy an object, passing reference, can not be replicated instance. The deep copy are copied to the internal reference objects, it is creating a new instance, and replicated instances.

For shallow copy of an object member variable is when the elementary data type when the member variable objects have two memory spaces, the assignment operator pass values, it can be replicated instance shallow copy. But when members of the variable object is a reference data type can not be achieved to copy the object.

Wild pointer: wild pointer to an object that has been deleted or application access limited memory area pointer. Empty pointers, wild pointers by simply unable to determine whether the NULL avoid, but only to try to reduce by develop good programming habits. For wild pointer operation can easily lead to errors.

When to use the C ++ copy constructor ? C ++ is used to generate a shallow copy note pointer field. The default copy constructor is shallow copy.

1. An object passed by value passed to the function thereof.

2. An object passed by value returned from the function.

3. An object needs to be initialized by another object.

C ++ copy constructor divided into shallow vs. deep copy two types of
shallow vs. deep copy main difference is whether to re-create the memory copy pointer.
If you do not create a memory address assignment only a pale copy,
create a new memory, the value of all the copy is a deep copy.
Shallow copy just copies the pointer has a pointer member under circumstances in which class address, will lead to two members of the pointers to the same memory, this will be a problem when and if separately delete release, and therefore need a deep copy.

Published 53 original articles · won praise 5 · Views 440

Guess you like

Origin blog.csdn.net/qq_45287265/article/details/104979554