我正在检查 this文章 它指出
Note: if a constructor finishes by throwing an exception, the memory associated with the object itself is cleaned up — there is no memory leak. For example:
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
}
}
我该如何解决这个问题?
对于更新可能造成的不便,我们深表歉意。
最佳答案
"... the destructor would not be called."
由于对象还未被视为已构造,在构造函数因异常而失败后,将不会调用析构函数。
对象分配和构造(仅仅是销毁)是不同的事情。
在抛出异常之前使用 new()
分配的任何对象都将泄漏。
You shouldn't manage these resources yourself, unless you're really, really, really need it, and are about 100% sure about what you're doing.
而是为来自 standard dynamic memory management library 的类成员使用合适的智能指针.
关于c++ - 构造函数通过抛出异常结束?是否存在内存泄漏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25962716/