Search code examples
c++lambda

RAII function invoke


Is there a class in standard library that will invoke provided function in its destructor? Something like this

class Foo
{
public:
 template<typename T>
 Foo(T callback)
 {
   _callback = callback;
 }
 ~Foo()
 {
   _callback();
 }
private:
 std::function<void()> _callback;
};
auto rai = Foo([](){ cout << "dtor";});

Solution

  • there is an experimental scope_exit


    example: https://godbolt.org/z/4r54GYo33