是否有任何技巧可以检测在执行另一个析构函数期间是否创建了一个对象?

odi*_*erd 11 c++ destructor stack-unwinding uncaught-exception

这是一个跟进的原因为什么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
}
Run Code Online (Sandbox Code Playgroud)

一次尝试可能是:

assert(!std::uncaught_exception());
Run Code Online (Sandbox Code Playgroud)

但是只有在因为异常而被调用析构函数时才会有效,而不是因为对象超出范围而被调用.

pal*_*pal 1

你无法检测到这一点,而且你也不想检测到。这不关你们班级的事。如果有人从 no except 析构函数调用你,他会捕获异常