c++ - try catch finally construct - 它是在 C++11 中吗?

标签 c++ c++11

<分区>

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

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

最佳答案

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

用法:

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

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

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

关于c++ - try catch finally construct - 它是在 C++11 中吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7779652/

相关文章:

c# - 制作 C++/MFC 应用程序以从其他应用程序中提取 AssemblyInfo?

c++ - 我如何在 C++ 中做一个事件?

c++ - shared_ptr, unique_ptr, ownership,在这种特殊情况下我是不是做得太过分了?

map - 为什么我的unordered_map自己订购?

c++ - 在共享内存中移动 boost::interprocess::string

c++ - 在 C 中模拟 std::bind

c++ - g++ __static_initialization_and_destruction_0(int, int) - 它是什么

c++ - 如何将模板化固定字符串传递给另一个类的构造函数的重载

c++ - std::ostream::write 有什么限制吗?

c++ - 如何使用 C++ boost 库为特定线程定义堆栈大小?