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