Home > database >  RAII function invoke
RAII function invoke

Time:10-29

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";});

CodePudding user response:

there is an experimental scope_exit


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

CodePudding user response:

You can use std::shared_ptr for that.

std::shared_ptr<void>(nullptr, [](void*){ std::cout << "dtor\n";});

See it online.

std::shared_ptr calls deleter even if managed pointer is nullptr, so there's no need to use any dummy pointer in there. However, personally I'd have strong concerns agains (ab)using std::shared_ptr in this way and I'd probably not let it through review. It's one big gotcha (although it may become an idiom if it's used all over a project).

CodePudding user response:

for implement it, I'd suggest not use type-erased std::function.

here is a possible implementation

template<typename F>
struct scope_exit{
    [[nodiscard]]
    scope_exit(F&& f):f(std::move(f)){}
    ~scope_exit(){f();}

    scope_exit(const scope_exit&)=delete;
    scope_exit& operator=(const scope_exit&)=delete;

    F f;
};
  • Related