• 深拷贝与浅拷贝


    #if 1

    #include <iostream>
    using namespace std;

    //深拷贝与浅拷贝
    class Person
    {
    public:
        Person()
        {
            cout << "Person默认构造函数调用" << endl;
        }

        Person(int age, int hight)
        {
            m_Age = age;
            //如果属性有在堆区开辟的,一定要自己提供拷贝构造函数,防止浅拷贝带来的问题。
            m_Height = new int(hight);
            cout << "Person有参构造函数调用" << endl;
        }

        //自己实现拷贝构造函数 解决浅拷贝带来的问题
        Person(const Person& p)
        {
            cout << "Person拷贝构造函数调用" << endl;
            m_Age = p.m_Age;
            //m_Height = p.m_Height;//编译器默认实现这行代码

            m_Height = new int(*p.m_Height);
            
        }

        ~Person()
        {
            //析构代码,将堆区开辟的数据做释放操作。
            if (m_Height != NULL)
            {
                delete m_Height;
                m_Height = NULL;
            }
            cout << "Person析构函数调用" << endl;
        }

        int m_Age;
        int* m_Height;//如果属性有在堆区开辟的,一定要自己提供拷贝构造函数,防止浅拷贝带来的问题。
    };

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

        Person p2(p1);//如果利用编译器提供的拷贝构造函数,会做浅拷贝操作。带来的问题是堆区的问题重复释放。
        //要利用深拷贝来解决

        cout << "p2的年龄为:" << p2.m_Age << ",身高为:" << *p2.m_Height << endl;
    }

    int main()
    {
        test01();
        system("pause");
        return 0;
    }

    #endif

  • 相关阅读:
    xlua游戏热更新(C#访问lua)
    数据可视化基础与应用-01-课程目标与职位分析
    《Qt5.9 C++开发指南》
    00 后搞视频号月入过万,怎么做?
    Django基础二静态文件和ORM
    SpringBoot实现SSMP整合
    集群所有进程查看脚本xcall.sh
    window下编译openssl
    Soul App Android一二三面凉经(2024)
    Win11一键重装系统后如何使用自带的故障检测修复功能
  • 原文地址:https://blog.csdn.net/WOSHIZHOUWANLI/article/details/125629651