Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
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
use of assert to check a particular situation! (throws error)
Policy based smart pointer
PriorQ
parallel_for_each
completed
Zahra_matrix
std::function ambiguity gcc
Hello World
stl_sizeof
4C test