我有以下代码:为什么不在异常未被捕获到时调用析构函数?
#include <iostream>
#include <vector>
#include <tr1/memory>
struct FooError {};
struct Foo
{
~Foo() { std::cerr << "~Foo() executed" << std::endl; }
explicit Foo(unsigned int index) { if (5 == index) throw FooError(index); };
};
int main() {
typedef std::tr1::shared_ptr<Foo> FooPtr;
std::vector<FooPtr> foos;
for (unsigned int index = 0; index < 20; ++index)
{
try
{
foos.push_back(FooPtr(new Foo(index)));
}
catch (const FooError&)
{
std::cerr << "FooError caught" << std::endl;
}
}
}
我看到一组执行~Foo()
当有try{} catch{}
块。如果没有异常处理程序,则不会打印任何内容。这是否意味着在处理异常时调用堆栈分配对象的析构函数?还是没有打印,因为std :: cerr缓冲问题?
+1。我没有意识到OP在谈论没有try/catch时的情况,认为这是关于何时抛出异常的问题。 – 2011-12-18 17:22:43
但是我现在删除的答案仍然很重要 - 'Foo'没有堆栈分配。 – 2011-12-18 17:23:20
我想知道为什么没有堆栈解绕发生。如果有几个块级别,并且在下级错误被捕获,那么我会因为FooPtr的aint释放而导致内存泄漏? – bananov 2011-12-18 17:31:33