C++ finally写法

template<class F>
class final_act {
public:
    explicit final_act(F f) noexcept: f_(std::move(f)), invoke_(true) {}

    final_act(final_act &&other) noexcept: f_(std::move(other.f_)), invoke_(other.invoke_) {
        other.invoke_ = false;
    }

    final_act(const final_act &) = delete;

    final_act &operator=(const final_act &) = delete;

    ~final_act() noexcept {
        if (invoke_) f_();
    }

private:
    F f_;
    bool invoke_;
};
template<class F>
inline final_act<F> _finally(const F &f) noexcept {
    return final_act<F>(f);
}
template<class F>
inline final_act<F> _finally(F &&f) noexcept {
    return final_act<F>(std::forward<F>(f));
}
#define concat1(a, b) a ## b
#define concat2(a, b) concat1(a,b)
#define _finally_object concat2(_finally_object_, __COUNTER__)
#define finally(func) auto _finally_object = _finally(func)
int abc = 0;
int main() {
    {
        abc = 1;
        auto exe = [&]() {
            abc = 2;
        };
        auto ddd = final_act<decltype(exe)>(exe);
    }
    {
        finally([&]() { abc = 3; });
        finally([&]() { abc = 4; });
    }
    abc = 5;
    std::cout << "test:abc=" << abc << std::endl;
    return 0;
}

猜猜abc是多少

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容