try catch finally 构造 - 是在 C++11 中吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7779652/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 17:28:39  来源:igfitidea点击:

try catch finally construct - is it in C++11?

c++c++11

提问by smallB

Possible Duplicate:
Does C++ support 'finally' blocks? (And what's this 'RAII' I keep hearing about?)

可能的重复:
C++ 是否支持“finally”块?(我一直听到的这个“RAII”是什么?)

Does try/catch/finally construct is supported in C++11?
I'm asking because I couldn't find anywhere information about it. Thanks.

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

回答by Luc Danton

Not an excuse to forgo RAII, but useful when e.g. using non RAII aware APIs:

不是放弃 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) };
}

Usage:

用法:

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

Note how you don't need a tryblock if you don't need to translate or otherwise handle exceptions.

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

While my example makes use of C++11 features, the same generic functionality was available with C++03 (no lambdas though).

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

回答by David Heffernan

C++11 does not add support for finally. The decision makers (especially Stroustrup) have for many many years expressed a preference for other idioms, i.e. RAII. I think it is exceptionally unlikely that C++ will ever include finally.

C++11 没有添加对finally. 多年来,决策者(尤其是Stroustrup)表达了对其他习语的偏好,即 RAII。我认为 C++ 极不可能包含finally.

回答by fredoverflow

You don't need finallyin C++ because C++ has RAIIwhich is much nicer.

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