浅拷贝与深拷贝

浅拷贝过程最大的问题是共享同一块内存,容易引发内存问题,下面这个例子就是浅拷贝在析构的时候出现段错误。

#include <iostream>
#include <cstring> // for strcpy_s
#include <thread>
class MyClass {
public:
    char* data;

    MyClass(const char* str) {
        data = new char[strlen(str) + 1];
        strcpy_s(data, strlen(str) + 1, str);
    }

    // 浅拷贝构造函数
    MyClass(const MyClass& other) {
        data = other.data;
    }

    // 深拷贝构造函数
    MyClass(const MyClass& other, bool deepCopy) {
        if (deepCopy) {
            data = new char[strlen(other.data) + 1];
            strcpy_s(data, strlen(other.data) + 1, other.data); 
        }
        else {
            data = other.data;
        }
    }

    ~MyClass() {
        delete[] data;
    }

    void print() const {
        std::cout << data << std::endl;
    }
};

int main() {
    MyClass obj1("Hello, World!");

    // 浅拷贝
    MyClass obj2(obj1);
    std::cout << "After shallow copy:" << std::endl;
    obj1.print();
    obj2.print();

    //修改obj2数据
    obj2.data[0] = 'a';
    std::cout << "After modifying obj2's data:" << std::endl;
    obj1.print(); // obj1不会被修改
    obj2.print();

    // 深拷贝
    MyClass obj3(obj1, true);
    std::cout << "After deep copy:" << std::endl;
    obj1.print();
    obj3.print();

    // 修改obj3的数据
    obj3.data[0] = 'b';
    std::cout << "After modifying obj3's data:" << std::endl;
    obj1.print(); // obj1不会被修改
    obj3.print();

    //在此之前程序正常输出,但是在程序退出的时候,析构函数导致浅拷贝过程中的内存释放出错。
    std::this_thread::sleep_for(std::chrono::seconds(3));
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

公孙无语

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

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

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

打赏作者

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

抵扣说明:

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

余额充值