尝试catch finally finally - 是否在C++ 11中?

sma*_*llB 5 c++ c++11

可能重复:
C++是否支持'finally'块?(我听到的'RAII'是什么?)

在C++ 11中是否支持try/catch/finally构造?
我问,因为我找不到任何关于它的信息.谢谢.

Luc*_*ton 18

放弃RAII不是借口,但在使用非RAII感知API时非常有用:

template<typename Functor>
struct finally_guard {
    finally_guard(Functor f)
        : functor(std::move(f))
        , active(true)
    {}

    finally_guard(finally_guard&& other)
        : functor(std::move(other.functor))
        , active(other.active)
    { other.active = false; }

    finally_guard& operator=(finally_guard&&) = delete;

    ~finally_guard()
    {
        if(active)
            functor();
    }

    Functor functor;
    bool active;
};

template<typename F>
finally_guard<typename std::decay<F>::type>
finally(F&& f)
{
    return { std::forward<F>(f) };
}
Run Code Online (Sandbox Code Playgroud)

用法:

auto resource = /* acquire */;
auto guard = finally([&resource] { /* cleanup */ });
// using just
// finally([&resource] { /* cleanup */ });
// is wrong, as usual
Run Code Online (Sandbox Code Playgroud)

请注意,try如果您不需要翻译或以其他方式处理异常,则不需要块.

虽然我的示例使用了C++ 11的功能,但C++ 03提供了相同的通用功能(尽管没有lambda).

  • 你如何保证析构函数不被调用两次? (2认同)

Dav*_*nan 13

C++ 11不支持finally.多年来,决策者(特别是Stroustrup)表达了对其他习语的偏好,即RAII.我认为C++不太可能包括在内finally.


fre*_*low 8

您不需要finally在C++中,因为C++具有更好的RAII.

  • 通过提供一个完整的疯狂片段,你无法真正显示最终的需要:p. (5认同)
  • 我不认为这是疯了.它清楚地表明,根据错误的情况需要采用不同的方法,最后是一种干净的方法.并且它不能像RAII一样干净利落地完成 (5认同)
  • 但RAII并不总是==最终. (3认同)