我去了this文章 ,並且聲明構造函數拋出異常完成?有沒有內存泄漏?
注:如果一個構造函數拋出一個異常,與本身清理對象相關的內存 完成 - 沒有內存泄漏 。例如:
void f()
{
X x; // If X::X() throws, the memory for x itself will not leak
Y* p = new Y(); // If Y::Y() throws, the memory for *p itself will not leak
}
我難以理解這一點,將不勝感激,如果有人可以澄清這一點。我嘗試了下面的例子,它顯示了在構造函數中不會調用析構函數的例外情況。
struct someObject
{
someObject()
{
f = new foo();
throw 12;
}
~someObject()
{
std::cout << "Destructor of someobject called";
}
foo* f;
};
class foo
{
public:
foo()
{
g = new glue();
someObject a;
}
~foo()
{
std::cout << "Destructor of foo";
}
private:
glue* g;
};
int main()
{
try
{
foo a;
}
catch(int a)
{
//Exception caught. foo destructor not called and someobject destrucotr not called.
//Memory leak of glue and foo objects
}
}
我該如何解決這個問題?
對不起,這可能是最新的版本。
析構函數未被調用,因爲對象從未正確構造。 – 2014-09-21 18:58:04