浅拷贝和深拷贝

浅拷贝:浅拷贝是指只复制对象的引用,而不是对象本身。当一个对象被浅拷贝时,复制出来的新对象和原对象共享相同的内存空间。这意味着,当修改新对象时,原对象也会受到影响。C++拷贝构造函数默认提供就是浅拷贝。

浅拷贝,代码中直接把obj1.m_ptr的地址赋值给obj2.m_ptr,两者共同指向一个内存空间,可以看到运行结果中,地址是一样的,内存图如下,浅拷贝容易导致程序崩溃,如下面例子我们用delete 了obj1指向的内存,那obj的指针就成了悬空指针,即指向一个不存在的内存区域,导致程序崩溃。

#include <iostream>
using namespace std;
class myclass {
public:
    myclass(int val) {
        m_ptr = new int(val);
    }
    myclass():m_ptr(nullptr) {

    }
    ~myclass() {
        delete m_ptr;
    }
    //复制构造函数
    myclass(const myclass& other) {
        m_ptr = other.m_ptr;
    }
    myclass& operator=(const myclass& other) {
        if (&other != this) {
            m_ptr = other.m_ptr;
        }
        return *this;
    }

public:
    int* m_ptr;
};
int main() {
    myclass obj1(10);
    //浅拷贝
    myclass obj2 = obj1;
    *obj2.m_ptr =20;

    cout << *obj1.m_ptr << endl;
    cout << *obj2.m_ptr << endl;
    cout << "obj1 address: " << obj1.m_ptr << endl;    
    cout << "obj2 address: " << obj2.m_ptr << endl;
    return 0;
}

运行结果

20
20
obj1 address: 0x25d2630
obj2 address: 0x25d2630

内存图

 深拷贝:深拷贝是指完全复制一个对象及其包含的所有数据,而不是仅复制其引用。当一个对象被深拷贝时,复制出来的新对象和原对象占用不同的内存空间,彼此独立。在 C++ 中,深拷贝通常需要自定义复制构造函数和赋值运算符。深拷贝可以避免浅拷贝带来的资源释放问题,但是同时也增加了性能的开销。

#include <iostream>
using namespace std;
class myclass {
public:
    myclass(int val) {
        m_ptr = new int(val);
    }
    myclass():m_ptr(nullptr) {

    }
    ~myclass() {
        delete m_ptr;
    }
    //复制构造函数
    myclass(const myclass& other) {
        m_ptr = new int(*other.m_ptr);
        memcpy(m_ptr,other.m_ptr,sizeof(*(other.m_ptr)));
    }
    myclass& operator=(const myclass& other) {
        //避免自我赋值
        if (&other != this) {
            //释放掉原来指向的资源 
            delete m_ptr;  
            m_ptr = new int(*other.m_ptr);
            memcpy(m_ptr,other.m_ptr,sizeof(*(other.m_ptr)));
        }
        return *this;
    }

public:
    int* m_ptr;
};
int main() {
    myclass obj1(10);
    //深拷贝
    myclass obj2;
    obj2 = obj1;
    *obj2.m_ptr = 20;

    cout << *obj1.m_ptr << endl;
    cout << *obj2.m_ptr << endl;
    cout << "obj1 address: " << obj1.m_ptr << endl;    
    cout << "obj2 address: " << obj2.m_ptr << endl;
    return 0;
}

运行结果

10
20
obj1 address: 0xec6330
obj2 address: 0xec6350

内存图

 有问题欢迎指出。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

晓晓知道了

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值