類為什么會出現析構兩次

#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; }