Created
January 19, 2017 23:14
-
-
Save ognian-/db31063d46345e5b47c3f35bb811ff76 to your computer and use it in GitHub Desktop.
c++11 finally block emulation via lambda
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
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