【C++小技巧 ---- defer 实现】

时间:2025-03-30 07:12:13
#pragma once #include <utility> template <typename T> struct MyDefer { MyDefer(T &&f) : f_(std::forward<T>(f)) {} ~MyDefer() { f_(); } MyDefer(const MyDefer&) = delete; MyDefer(MyDefer&&) = default; MyDefer&operator=(const MyDefer&) = delete; MyDefer&operator=(MyDefer&&) = delete; T f_; }; template <typename T> MyDefer<T> make_defer(T &&f) { return MyDefer<T>(std::forward<T>(f)); } #define CAT1(x, y) x##y #define CAT2(x, y) CAT1(x, y) #define defer_obj_name CAT2(defer_obj, __COUNTER__) #define defer(expr) auto defer_obj_name = make_defer([&]() { expr; });