【发布时间】:2014-01-05 15:57:20
【问题描述】:
我想知道如果一个对象是动态分配的,构造函数抛出异常,这个对象还需要删除吗?
class Doom
{
public:
Doom() { throw 0; }
private:
int pad;
};
int main()
{
try
{
// memory is allocated for Doom but construction fails
// is the memory deallocated if construction fails here ?
Doom* doom = new Doom();
}
catch(int ex)
{
// ...
}
}
【问题讨论】:
-
使用
unique_ptr。永远不要考虑删除内存或再次泄漏。 -
@Dave: 使用
unique_ptr是不够的 -foo(unique_ptr(new bar()), unique_ptr(new bar()));仍然可以泄漏。你需要make_unique/make_shared。 -
@JoeGauterin:想详细说明这将如何泄漏?编辑:啊,我想我现在看到了,调用了 new bar(),然后在为另一个 bar 构造 unique_ptr 之前调用了另一个 new bar(),但是这个抛出异常,导致前一个泄露。
-
这篇 Herb Sutter 文章深入讲解 - herbsutter.com/2013/05/29/gotw-89-solution-smart-pointers
标签: c++