#include<iostream>
using namespace std;
class A{
public:
A(){cout << "A() Constructor " << endl;
throw 1;
}
};
int main(){
A* p=0;
cout << p << endl; // p value is 0
try{
p=new A(); // object is not fully constructed, no address is returned to p. for future deallocation
}
catch(...){cout << "Exception" << endl;}
cout << p << endl; // this will output that p has the value 0,proof that no address was returned to p.
}
存儲器被分配用於在堆中的目的,存儲器的地址被傳遞到構造 但當構造throw 1;
然後的對象類型A
不會被認爲是完全構建的對象。所以沒有 指針會返回指針p。隨時糾正我,如果我瞭解錯誤的東西。
問題:
1)所以我的問題是如何在這種情況下可能釋放內存的目的。我不是在談論 析構函數調用,但內存釋放。
2)當我在main
函數內部創建類型爲A
的本地對象時,該怎麼辦。顯然它也不會被完全構建。何時該對象被釋放(在調用完全構造的子對象的析構函數之後)。
你不能刪除它,因爲p是空指針,並且對象A被分配到的內存地址沒有被傳遞給這個指針,因爲在構造函數中拋出了異常 – AlexDan
正確的方法做它就叫做共享指針。 – Florian