try catch finally construct - 是在C ++ 11? [英] try catch finally construct - is it in C++11?

查看:356
本文介绍了try catch finally construct - 是在C ++ 11?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

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

/ catch / finally构造在C ++ 11中支持?

我问的是因为我找不到任何有关它的信息。
谢谢。

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

推荐答案

不是放弃RAII的借口,使用非RAII感知的API:

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

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) };
}

用法:

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

注意你不需要<$

虽然我的例子使用C ++,但是如果你不需要翻译或处理异常,请尝试 11特性,使用C ++ 03提供了相同的通用功能(没有lambdas)。

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

这篇关于try catch finally construct - 是在C ++ 11?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆