前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++ 中的深拷贝与浅拷贝理解

C++ 中的深拷贝与浅拷贝理解

作者头像
耕耘实录
发布2022-05-09 16:12:36
2900
发布2022-05-09 16:12:36
举报
文章被收录于专栏:耕耘实录耕耘实录

● 浅拷贝,简单的赋值拷贝操作。系统利用编译器提供的拷贝构造函数,会做浅拷贝操作。会造成堆区内存重复释放而导致程序崩溃,代码如下:

代码语言:javascript
复制
#include<iostream>

using namespace std;

class Person {
public:
    Person() {
        cout << "Person的默认构造函数调用" << endl;
    }

    Person(int age, int height) {
        m_Age = age;
        m_Height = new int(height);
        cout << "Person的有参构造函数调用" << endl;
    }

    ~Person() {
        if (m_Height != NULL) {
            delete m_Height;
            m_Height = nullptr;
        }
        cout<<"析构函数调用"<<endl;
    }

    int m_Age;
    int *m_Height;

};

void test() {
    Person p1(18,190);
    cout << "p1的年龄为: " << p1.m_Age << endl;
    cout << "p1的身高为: " << *p1->m_Height << endl;
    Person p2(p1);
    cout << "p2的年龄为: " << p2.m_Age << endl;
    cout << "p2的身高为: " << *p2.m_Height << endl;
}

int main() {
    test();
}

● 深拷贝,在堆区重新申请空间,进行拷贝操作。重新拷贝构造函数后,解决问题,代码如下:

代码语言:javascript
复制
#include<iostream>

using namespace std;

class Person {
public:
    Person() {
        cout << "Person的默认构造函数调用" << endl;
    }

    Person(int age, int height) {
        m_Age = age;
        m_Height = new int(height);
        cout << "Person的有参构造函数调用" << endl;
    }

    Person(Person &p){
        cout<<"Person拷贝构造函数调用"<<endl;
        m_Age = p.m_Age;
        m_Height = new int(*p.m_Height);
    }

    ~Person() {
        if (m_Height != NULL) {
            delete m_Height;
            m_Height = nullptr;
        }
        cout<<"析构函数调用"<<endl;
    }

    int m_Age;
    int *m_Height;

};

void test() {
    Person p1(18,190);
    cout << "p1的年龄为: " << p1.m_Age << endl;
    cout << "p1的身高为: " << *p1.m_Height << endl;
    Person p2(p1);
    cout << "p2的年龄为: " << p2.m_Age << endl;
    cout << "p2的身高为: " << *p2.m_Height << endl;
}

int main() {

    test();

}

注意:如果属性有在堆区开辟的,一定要提供拷贝构造函数,防止浅拷贝带来的问题。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2022-01-20,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档