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.

  • Copy Constructor
  • Default assignment operator

// Copy Constructor
Geeks Obj1[Obj];
or
Geeks Obj1 = Obj;

// Default assignment operator
Geeks Obj2;
Obj2 = Obj1;

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.
This will create ambiguity and run-time errors, dangling pointer. Since both objects will reference to the same memory location, then change made by one will reflect those change in another object as well. Since we wanted to create a replica of the object, this purpose will not be filled by Shallow copy. 
Note: C++ compiler implicitly creates a copy constructor and overloads assignment operator in order to perform shallow copy at compile time.
 

Shallow Copy of object if some variables are defined in heap memory, then:

Below is the implementation of the above approach:

C++

#include

using namespace std;

class box {

private:

    int length;

    int breadth;

    int height;

public:

    void set_dimensions[int length2, int breadth2,

                        int height1]

    {

        length = length2;

        breadth = breadth2;

        height = height1;

    }

    void show_data[]

    {

        cout

Bài Viết Liên Quan

Chủ Đề