I want to implement a finally
block in my C++ program, and the language certainly has the tools to do it if not a native facility. I was wondering what the best way
An alternative solution using std::function. No factory function needed. No per-use template instantiation (better footprint?!). No std::move and && stuff needed, no auto needed ;)
class finally
{
std::function m_finalizer;
finally() = delete;
public:
finally( const finally& other ) = delete;
finally( std::function finalizer )
: m_finalizer(finalizer)
{
}
~finally()
{
std::cout << "invoking finalizer code" << std::endl;
if( m_finalizer )
m_finalizer();
}
};
Usage:
int main( int argc, char * argv[] )
{
bool something = false;
try
{
try
{
std::cout << "starting" << std::endl;
finally final([&something]() { something = true; });
std::cout << "throwing" << std::endl;
throw std::runtime_error("boom");
}
catch(std::exception & ex )
{
std::cout << "inner catch" << std::endl;
throw;
}
}
catch( std::exception & ex )
{
std::cout << "outer catch" << std::endl;
if( something )
{
std::cout << "works!" << std::endl;
}
else
{
std::cout << "NOT working!" << std::endl;
}
}
std::cout << "exiting" << std::endl;
return 0;
}
Output:
starting
throwing
invoking finalizer code
inner catch
outer catch
works!
exiting