1.C++類的深拷貝與淺拷貝


#?C++類的深拷貝與淺拷貝

堆區(qū)的內(nèi)存重復(fù)釋放


改進,拷貝構(gòu)造都開辟新的內(nèi)存

```

#include<iostream>


using namespace std;


class Person

{

????public:

????Person()

????{

????????cout << "Person默認構(gòu)造函數(shù)調(diào)用" << endl;

????}

????Person(int age, int height)

????{

????????cout << "Person有參構(gòu)造函數(shù)調(diào)用" << endl;

????????m_Age = age;

????????m_Height = new int(height);

????}

Person(const Person & p)

{

????????cout << "Person拷貝構(gòu)造函數(shù)調(diào)用" << endl;

????? ? //m_Height = p.m_Height; 編譯器默認實現(xiàn)這個代碼

????????//深拷貝操作

????????m_Height = new int(*p.m_Height);//*p.m_Height 解引用,得到參數(shù)存儲的內(nèi)存地址

????}

//淺拷貝帶來堆區(qū)的重復(fù)釋放

~Person()

{ //析構(gòu)代碼, 將堆區(qū)開辟數(shù)據(jù)做釋放操作

????if (m_Height != NULL)

{

delete m_Height;

//放置野指針的出現(xiàn),先置空

m_Height = NULL;

}

????cout << "Person析構(gòu)函數(shù)調(diào)用" << 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的年齡為: " << p1.m_Age << "2身高為: " << *p1.m_Height << endl;

}

int main()

{

????test01();

????system("pause");

????return 0;

}

```

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容