Shallow copy và deep copy trong c++
In general, creating a copy of an object means to create an exact replica of the object having the same literal value, data type, and resources. Show
Depending upon the resources like dynamic memory held by the object, either we need to perform Shallow Copy or Deep Copy in order to create a replica of the object. In general, if the variables of an object have been dynamically allocated, then it is required to do a Deep Copy in order to create a copy of the object. Shallow Copy:In shallow copy, an object is created by simply copying the data of all variables of the original object. This works well if none of the variables of the object are defined in the heap section of memory. If some variables are
dynamically allocated memory from heap section, then the copied object variable will also reference the same memory location. Shallow Copy of object if some variables are defined in heap memory, then: Below is the implementation of the above approach: C++
Output: Length = 14 Breadth = 12 Height = 16 Length = 14 Breadth = 12 Height = 16 Length = 14 Breadth = 12 Height = 16 Deep Copy:In Deep copy, an object is created by copying data of all variables, and it also allocates similar memory resources with the same value to the object. In order to perform Deep copy, we need to explicitly define the copy constructor and assign dynamic memory as well, if required. Also, it is required to dynamically allocate memory to the variables in the other constructors, as well. Below is the implementation of the above approach: C++
Output: Length = 12 Breadth = 14 Height = 16 Length = 12 Breadth = 14 Height = 16 Let us see the differences in a tabular form -:
|