这有点是对为什么Alexandrescu不能使用std::uncaught_exception()来实现ScopeGuard11中的SCOPE_FAIL?的跟进。
我想检测是否有人在另一个类的析构函数中(或在调用堆栈的某个活动析构函数中)创建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());
但是这仅在析构函数由于异常而被调用时才有效,如果它是因为对象超出范围而被调用,则不起作用。
MyClass
的构造函数中检查堆栈,以查找OtherClass
的析构函数。我个人认为这太费力了... 而且会产生错误。 - Synxis