C++类成员的深拷贝和浅拷贝


类为什么会出现析构两次

#include <iostream>
using namespace std;

class Test{
private:
    int* p;
public:
    Test(int x)//构造函数
    {
        this->p=new int(x);
        cout << "对象被创建" << endl;
    }

    ~Test()//析构函数
    {
        if (p != NULL)
        {
            delete p;
        }
        cout << "对象被释放" << endl;
    }
    int getX() { return *p; }
};

int main()
{
    Test a(10);
    Test b = a;//会调用默认的拷贝构造函数
    //在析构b的时候,由于a中的指针p已经被析构了,无法再次析构
    return 0;
}
浅拷贝出现的问题

设计到类中的成员变量是new的指针的时候,需要在类中加入深拷贝构造函数

#include <iostream>
using namespace std;

class Test
{
private:
    int* p;
public:
    Test(int x)
    {
        this->p=new int(x);
        cout << "对象被创建" << endl;
    }
    ~Test()
    {
        if (p != NULL)
        {
            delete p;
        }
        cout << "对象被释放" << endl;
    }
    int getX() { return *p; }
    
    //深拷贝(拷贝构造函数)
    Test(const Test& a)
    {
        this->p = new int(*a.p);
        cout << "对象被创建" << endl;
    }
    //浅拷贝(拷贝构造函数)
    //Test(const Test& a)
    //{
    //  this->p = a.p;
    //  cout << "对象被创建" << endl;
    //}
};

int main()
{
    Test a(10);
    //我们手动的写拷贝构造函数,C++编译器会调用我们手动写的
    Test b = a;
    return 0;
}
解决的办法

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM