09 C++ 深拷贝与浅拷贝

94 阅读1分钟

Android Ndk 学习笔记(目录)

class Kaobei{

public:

    int age;
    char * name;

    Kaobei() { cout << "空参数构造函数" << endl; }

    Kaobei(char * name) :Kaobei(name, 99) {
        cout << "一个参数构造函数 this:" << this << endl;
    }

    Kaobei(char * name, int age) {
        cout << "二个参数构造函数 this:" << this << endl;
        //在堆空间中开辟的变量 ,拷贝时 需要自定义拷贝函数进行深拷贝 , 默认的是浅拷贝
        this->name = (char *)malloc(sizeof(char *)* 10);
        strcpy(this->name, name);
        this->age = age;
    }

    ~Kaobei() {
        cout << "析构函数执行 &this->name:" << this->name << endl;
        free(this->name);
        this->name = NULL;
    }
    
    Kaobei(const Kaobei & stu) {
        
        cout << "拷贝构造函数 &stu:" <<&stu << " this:" <<this << endl;
        // 【浅拷贝】:新地址name  旧地址name 指向同一个空间,会造成,重复free的问题,引发奔溃
        // 新地址name = 旧地址 (浅拷贝)
        // this->name = stu.name;
        // 【深拷贝】
        this->name = (char *)malloc(sizeof(char *)* 10);
        strcpy(this->name, name);

        this->age = stu.age;

        cout << "拷贝构造函数2 this->name:" << this->name << "  stu.name:" << stu.name << endl;


    }


    
};