这是对 Why can't Alexandrescu use std::uncaught_exception() to implement SCOPE_FAIL in ScopeGuard11? 的跟进
我想检测是否有人在另一个类的析构函数中创建 MyClass
(或者在调用堆栈中某处使用事件析构函数)。
class MyClass
{
public:
MyClass(){
assert(???what to put here????);
}
}
void f(){
MyClass m; //whether this asserts should be context dependant
}
class OtherClass{
~OtherClass(){
MyClass m; //this should assert
f(); //this should too;
}
}
int main()
{
MyClass m; //this should not assert
f(); //this should also not assert
}
一个尝试可能是:
assert(!std::uncaught_exception());
但这仅在析构函数因异常而被调用时才有效,如果因对象超出范围而被调用则无效。
最佳答案
您无法检测到这一点,您也不想检测到。这不关你类(class)的事。如果有人从 noexcept 析构函数调用你,他会捕获异常
关于c++ - 是否有任何技巧可以检测在执行另一个析构函数期间是否创建了一个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14939825/