【发布时间】:2014-11-15 17:57:39
【问题描述】:
我正在浏览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
}
}
我该如何解决这个问题?
对于更新可能造成的不便,我们深表歉意。
【问题讨论】:
-
没有调用析构函数,因为对象从未正确构造。
标签: c++ exception memory-leaks constructor