我去了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