堆栈展开时使用RAII是否安全?

use*_*289 3 c++ destructor exception raii stack-unwinding

class AutoSomething
{
public:
    AutoSomething(Object& ob)
        : object_(object)
    {}

    ~AutoSomething()
    {
        object_.some_callback();
    }

private:
    Object& object_;
};

.........

void Object::some_function()
{
    AutoSomething some(*this);

    some_function_which_may_throw_exception();
}
Run Code Online (Sandbox Code Playgroud)

问题是 - 当AutoSomething的析构函数被调用时,Object的状态是否正常?

Rei*_*ica 6

栈展开是为其RAII是摆在首位发明situtation.所以它肯定是适当的工具.

在您的特定情况下,没有理由为什么代码应该行为不正确.如果some_callback依赖于实际抛出Object时不保持内部不变量的唯一问题可能会出现some_function_which_may_throw_exception,但这会导致特定代码的问题并且与C++本身无关.