Created
March 9, 2013 06:24
-
-
Save eahydra/5123092 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef SCOPE_EXIT_HPP_ | |
#define SCOPE_EXIT_HPP_ | |
#include <functional> | |
namespace base { | |
template <typename handler_t> | |
class scope_exit { | |
private: | |
handler_t handler_; | |
bool dismissed_; | |
private: // noncopyable | |
scope_exit(scope_exit const&); | |
scope_exit& operator=(scope_exit const&); | |
public: | |
explicit scope_exit(handler_t&& handler) | |
: handler_(std::forward<handler_t>(handler)), dismissed_(false) { | |
} | |
~scope_exit() { | |
if(!dismissed_) { | |
handler_(); | |
} | |
} | |
scope_exit(scope_exit&& rhs) | |
: handler_(std::move(rhs.handler_)), dismissed_(rhs.dismissed_) { | |
} | |
scope_exit& operator=(scope_exit&& rhs) { | |
if (&rhs != this) { | |
handler_ = std::move(rhs.handler_); | |
} | |
return *this; | |
} | |
void dismiss() { | |
dismissed_ = true; | |
} | |
}; | |
template <typename handler_t> | |
inline scope_exit<handler_t> make_scope_exit(handler_t&& handler) | |
{ | |
return scope_exit<handler_t>(std::forward<handler_t>(handler)); | |
} | |
} // namespace base | |
#define SCOPEGUARD_LINENAME_CAT(name, line) name##line | |
#define SCOPEGUARD_LINENAME(name, line) SCOPEGUARD_LINENAME_CAT(name, line) | |
#define ON_SCOPE_EXIT(callback) auto SCOPEGUARD_LINENAME(EXIT, __LINE__) = base::make_scope_exit(callback) | |
#endif // SCOPE_EXIT_HPP_ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment