Skip to content

Instantly share code, notes, and snippets.

@ognian-
Created January 19, 2017 23:14
Show Gist options
  • Save ognian-/db31063d46345e5b47c3f35bb811ff76 to your computer and use it in GitHub Desktop.
Save ognian-/db31063d46345e5b47c3f35bb811ff76 to your computer and use it in GitHub Desktop.
c++11 finally block emulation via lambda
struct finally {
inline explicit finally(const std::function<void()>& code) noexcept: m_code{code} {}
inline ~finally() noexcept { try { m_code(); } catch(...) {} }
private:
finally(const finally&) = delete;
finally(finally&&) = delete;
finally& operator=(const finally&) = delete;
finally& operator=(finally&&) = delete;
std::function<void()> m_code;
};
/////////////////////////////////////////////////////////////////////
Usage:
int example() {
finally cleanup([] {
std::cout << "Cleaned up" << std::endl;
});
return 42;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment