Last active
December 14, 2015 04:48
-
-
Save kyle-go/5030483 to your computer and use it in GitHub Desktop.
scope guard
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 SCLOUD_SCOPE_GUARD_H_ | |
#define SCLOUD_SCOPE_GUARD_H_ | |
#include <functional> | |
namespace scloud{ | |
class ScopeGuard | |
{ | |
public: | |
explicit ScopeGuard(std::function<void(void)> onExitScope) | |
: doExit_(onExitScope), cancel_(false){} | |
~ScopeGuard() { | |
if(!cancel_) { | |
doExit_(); | |
} | |
} | |
void cancel() { | |
cancel_ = true; | |
} | |
private: | |
//disable copy | |
ScopeGuard(const ScopeGuard&); | |
void operator=(const ScopeGuard&); | |
std::function<void(void)> doExit_; | |
bool cancel_; | |
}; | |
}//end namespace | |
#define SCLOUD_CAT_STRING(name, line) name##line | |
#define SCLOUD_XSOCPEGUARD_LOCK_CAT(name, line) SCLOUD_CAT_STRING(name,line) | |
#define SCLOUD_SCOPE_EXIT scloud::ScopeGuard SCLOUD_XSOCPEGUARD_LOCK_CAT(ScopeGuard, __LINE__) | |
#endif //SCLOUD_SCOPE_GUARD_H_ | |
/*! | |
@brief how to use it. | |
① | |
SomeClass * p = new SomeClass; | |
SCLOUD_SCOPE_EXIT([](){delete p;}); | |
... | |
② | |
HANDLE h = CreateFile(...); | |
scloud::ScopeGuard guard([](){CloseHandle(h);};); | |
if (h == INVALIDE_HANDLE) { | |
guard.cancel(); | |
} | |
*/ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment