What is the most elegant solution for calling a function automatically when leaving a scope? My current approach (see below) works but I guess there should be something more general as writing a custom class for this.
#include <iostream>
#include <functional>
using namespace std;
class DoInDtor
{
public:
typedef function<void()> F;
DoInDtor(F f) : f_(f) {};
~DoInDtor() { f_(); }
private:
F f_;
};
void foo()
{
DoInDtor byeSayerCustom([](){ cout << "bye\n"; });
auto cond = true; // could of course also be false
if ( cond )
return;
return;
}
int main()
{
foo();
}
Sure, one could abuse std::unique_ptr and its custom deleter, but since I am not really acquiring a resource here, that does not sound great to me either in terms of code readability. Any suggestions?
DoInDtor
object in each scope. What are you trying to achieve? – Constipate