Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Scope guarding
Language:
Ada
Assembly
Bash
C#
C++ (gcc)
C++ (clang)
C++ (vc++)
C (gcc)
C (clang)
C (vc)
Client Side
Clojure
Common Lisp
D
Elixir
Erlang
F#
Fortran
Go
Haskell
Java
Javascript
Kotlin
Lua
MySql
Node.js
Ocaml
Octave
Objective-C
Oracle
Pascal
Perl
Php
PostgreSQL
Prolog
Python
Python 3
R
Rust
Ruby
Scala
Scheme
Sql Server
Swift
Tcl
Visual Basic
Layout:
Vertical
Horizontal
//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); add_element(ints, 5); add_element(ints, 8); } catch(...) { } std::cout<<"Listing added elements...\n"; for(const auto &i : ints) { std::cout<<*i<<" "; } std::cout<<'\n'; }
g++
Show compiler warnings
[
+
] Compiler args
[
+
]
Show input
Compilation time: 0.48 sec, absolute running time: 0.14 sec, cpu time: 0 sec, memory peak: 3 Mb, absolute service time: 0.63 sec (cached)
fork mode
|
history
|
discussion
Listing added elements... 3 5 8 Freeing 3 elements...