Learning: Classes and Objects - deep and shallow copy copy

Deep copy and shallow copy:

Shallow copy: copy operation simple assignment

Deep copy: reapply heap space, copying operation

Deep copy is to solve the problems caused by shallow copy produced

Shallow copy:

We look at this code:

#include<iostream>
#include<string>

using namespace std;

class Person {

public:

    Person() {
        cout << "这是无参构造函数" << endl;
    }
        
    Person(int age, int height) {
        cout << "这是有参构造函数" << endl;
        this->my_Age = age;
        this->my_height = new int(height);
    }
    
    ~Person() {
        if (this->my_height != NULL) {
            delete my_height;
            my_height = NULL;
        }
        cout << "这是析构函数" << endl;
    }

public:
    int my_Age;
    int * my_height;
};

void test01() {
    Person p1(18,160); //进行有参构造函数
    Person p2(p1); //进行拷贝构造函数
    cout << "p1的年龄为 " << p1.my_Age << ", p1的身高为 " << *(p1.my_height) << endl;
    cout << "p2的年龄为 " << p2.my_Age << ", p2的身高为 " << *(p2.my_height) << endl;

}

int main() {
    test01();
    
    system("pause");
    return 0;
}

We will find time to run the code above will get an error, the reason is that when the destructor, p2 will complete the implementation of the * my_heightpoints of the memory space to be released, the consequences would lead to the release of execution time when p1 can not find memory space caused by error, this time a deep copy can help us solve this problem shallow copy, in my understanding, the shallow copy of meaning can be understood as a function of the default copy function to copy the object after receiving identical to, All the same, it will inevitably lead to competition for similar problems, here 'vie' can be understood as the release of memory.

So deep copy came out, we can generate a new space for the object attribute of the stack pointer by defining area copying function.

Modify the code as follows: define their own copies of the function can

Person(const Person& p) { //定义拷贝函数
    this->my_Age = p.my_Age; //默认的拷贝函数,我们这边自己定义也要加上
    //this->my_height = p.my_height; //默认的拷贝函数,我们这边需要重写,所以这条注释
    this->my_height = new int(*(p.my_height)); //让我们的my_height存一个全新的栈区的地址
}

Guess you like

Origin www.cnblogs.com/zpchcbd/p/11863202.html