August 2017
Intermediate to advanced
438 pages
14h 19m
English
C++ uses the RAII pattern instead of try {} finally{} construction. The Boost.ScopeExit library was designed to allow user definition of RAII wrappers right in the function body:
#include <boost/scope_exit.hpp> #include <cstdlib> #include <cstdio> #include <cassert> int main() { std::FILE* f = std::fopen("example_file.txt", "w"); assert(f); BOOST_SCOPE_EXIT(f) { // Whatever happened in outer scope, this code will be executed // and file will be correctly closed. std::fclose(f); } BOOST_SCOPE_EXIT_END // Some code that may throw or return. // ... }
Read now
Unlock full access