C++11 scope exit guard, a good idea?

前端 未结 10 819
囚心锁ツ
囚心锁ツ 2020-12-08 05:00

I\'ve written a small utility class for C++11 which I use as a scope guard for easier handling of exception safety and similar things.

Seems somewhat like a hack. Bu

10条回答
  •  旧时难觅i
    2020-12-08 05:19

    Using Boost:

    #include 
    
    template
    class ScopeGuardDetails {
        const Fn m_fn;
    public:
        constexpr ScopeGuardDetails(Fn &&fn) : m_fn(fn) {}
        ~ScopeGuardDetails() { m_fn(); }
    };
    #define ScopeGuardName BOOST_PP_CAT(BOOST_PP_CAT(__scope_guard, _), BOOST_PP_CAT(BOOST_PP_CAT(__LINE__, _), __COUNTER__))
    #define defer(stmt) const auto ScopeGuardName = [](const auto _fn) { \
        return ScopeGuardDetails { std::move(_fn) }; \
    }([&] { stmt });
    

    Usage:

    if (gdiplus::GdiplusStartup(&token, &startupInput, nullptr) == Gdiplus::Ok) {
        defer({
            gdiplus::GdiplusShutdown(token);
        });
        ...
    }
    

提交回复
热议问题