Last active
August 29, 2015 14:15
-
-
Save santa4nt/68f4ab30a5cb77b88ba8 to your computer and use it in GitHub Desktop.
A sample C++11 idiom for RAII scoped action.
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
#include <iostream> | |
#include <functional> | |
using namespace std; | |
class ScopedAction | |
{ | |
public: | |
ScopedAction(function<void()> f) : func_(f) {} | |
~ScopedAction() { func_(); } | |
private: | |
function<void()> func_; | |
}; | |
static void print_function_entry(const string &name) | |
{ | |
cout << "Function entry: " << name << endl; | |
} | |
static void print_function_exit(const string &name) | |
{ | |
cout << "Function exit: " << name << endl; | |
} | |
// plain ol' function with no exception | |
void f() throw() | |
{ | |
const string fname("f()"); | |
print_function_entry(fname); | |
ScopedAction sa([=]()->void { | |
print_function_exit(fname); | |
}); | |
{ | |
// ... | |
} | |
cout << "Before exit: " << fname << endl; | |
} | |
// premature return | |
void f_exit() throw() | |
{ | |
const string fname("f_exit()"); | |
print_function_entry(fname); | |
ScopedAction sa([=]()->void { | |
print_function_exit(fname); | |
}); | |
{ | |
// ... | |
// something happened, must return fast | |
return; | |
} | |
// will not get reached | |
cout << "Before exit: " << fname << endl; | |
} | |
// throw before return | |
void f_throw() | |
{ | |
const string fname("f_throw()"); | |
print_function_entry(fname); | |
ScopedAction sa([=]()->void { | |
print_function_exit(fname); | |
}); | |
{ | |
// ... | |
throw string("An exception occurred."); | |
} | |
// will not get reached | |
cout << "Before exit: " << fname << endl; | |
} | |
int main() | |
{ | |
f(); | |
f_exit(); | |
try | |
{ | |
f_throw(); | |
} | |
catch (string &exc_str) | |
{ | |
cout << "Caught an exception: " << exc_str << endl; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment