09 C++ 深拷贝与浅拷贝

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;


    }


    
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值