【发布时间】:2015-02-01 20:28:47
【问题描述】:
是否可以在堆栈展开期间销毁的对象的析构函数中使用 std::current_exception?
Documentation on cppreference 说:
如果在异常处理期间(通常在 catch 子句中)调用,则捕获当前异常对象 (...)
但我不清楚堆栈展开是否是异常处理的一部分。
在 stackoverflow 上的一些 highest-ranked answer 中,作者认为这是可能的。
我对我的编译器 (g++ (Ubuntu 4.8.2-19ubuntu1) 4.8.2) 做了一些测试,似乎在这种情况下 std::current_exception 返回空指针。
#include <exception>
#include <stdexcept>
#include <iostream>
struct A
{
~A()
{
std::clog << "in destructor"<<std::endl;
std::clog << "uncaught_exception: " << std::uncaught_exception() << std::endl;
std::clog << "current_exception: " << (bool)std::current_exception() << std::endl;
}
};
int main(int argc, char **)
{
try
{
A aa;
std::clog << "before throw"<<std::endl;
if(argc>1)
throw std::runtime_error("oh no");
}
catch(...)
{
std::clog << "in catch block"<<std::endl;
std::clog << "uncaught_exception: " << std::uncaught_exception() << std::endl;
std::clog << "current_exception: " << (bool)std::current_exception() << std::endl;
}
return 0;
}
输出是:
before throw
in destructor
uncaught_exception: 1
current_exception: 0
in catch block
uncaught_exception: 0
current_exception: 1
有人知道标准是怎么说的吗?
【问题讨论】:
标签: c++ c++11 exception-handling