Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #ifndef TOKEN_PASTE
- #define TOKEN_PASTE(x, y) x##y
- #define TOKEN_PASTE2(x, y) TOKEN_PASTE(x, y)
- #endif
- template <typename L>
- struct scope_guard
- {
- L l_;
- bool invoked_{false};
- scope_guard(L &&l)
- : l_(std::move(l))
- {
- }
- ~scope_guard()
- {
- invoke();
- }
- void invoke()
- {
- if (!invoked_)
- {
- l_();
- invoked_ = false;
- }
- }
- void cancel()
- {
- invoked_ = true;
- }
- };
- template <typename T>
- inline auto make_scope_guard(T &&l)
- {
- return scope_guard<T>(std::forward<T>(l));
- }
- #define DEFER(...) auto TOKEN_PASTE2(__deferred, __COUNTER__) = make_scope_guard([&] { __VA_ARGS__ });
- int main()
- {
- int fd = open("/proc/self/pagemap", O_RDONLY|O_LARGEFILE);
- // DEFER(close(fd););
- // or
- // auto g = make_guard([fd]{ close(fd); });
- //
- // potentially g.cancel() or g.invoke() if needed
- return 0;
- }
Add Comment
Please, Sign In to add comment