Run Code
|
API
|
Code Wall
|
Users
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Blog
Scope guarding
//Title of this code #include <iostream> #include <vector> template<class Fun> class ScopeGuard { private: Fun f_; bool active_; private: ScopeGuard(const ScopeGuard &); ScopeGuard & operator = (const ScopeGuard &); public: ScopeGuard(Fun f) : f_(std::move(f)), active_(true) { } ScopeGuard(ScopeGuard &&other) : f_(std::move(other.f_)), active_(other.active_) { other.dismiss(); } ~ScopeGuard() { if (active_) { f_(); } } void dismiss() { active_ = false; } }; template<class Fun> ScopeGuard<Fun> scope_guard(Fun f) { return ScopeGuard<Fun>(std::move(f)); } #define CONCATENATE_IMPL(a, b) a##b #define CONCATENATE(a, b) CONCATENATE_IMPL(a, b) #define ANONYMOUS CONCATENATE(_, __LINE__) #define SCOPE_EXIT(code) auto ANONYMOUS = scope_guard([&]code); #define DEFINE_ROLLBACK(name, code) auto name = scope_guard([&]code); #define DISMISS_ROLLBACK(name) name.dismiss() void add_element(std::vector<int*> &v, int val) { int *p = new int(val); DEFINE_ROLLBACK(free_p, {std::cout<<"Freeing p...\n"; free(p);}); //throw "r"; v.push_back(p); DEFINE_ROLLBACK(r, {std::cout<<"Removing inserted element...\n"; v.pop_back();}); //throw "r"; DISMISS_ROLLBACK(r); DISMISS_ROLLBACK(free_p); } int main() { std::vector<int*> ints; SCOPE_EXIT( { std::cout<<"Freeing "<<ints.size()<<" elements...\n"; for(const auto &i : ints) { free(i); } }); try { add_element(ints, 3); } catch(...) { } for(const auto &i : ints) { std::cout<<*i<<" "; } std::cout<<'\n'; }
run
|
edit
|
history
|
help
0
Please
log in
to post a comment.
Bitset Operators
Sliding Game
2
Best way for getting more precision no.
simple use of templete
Gauss 4x4
Policy based smart pointer
Collatz Conjecture
Simple use of function templete and namespace
reverseKNode
Please log in to post a comment.