Home > Blockchain >  Is there a standard way to create a sharable objects with a custom destructor?
Is there a standard way to create a sharable objects with a custom destructor?

Time:01-29

Is there a standard type that looks like a std::shared_ptr in all aspects except actually pointing to anything?

I'm looking for something that's copyable/movable, typesafe, ref-counted, easily constructible with a custom deleter.

I just don't need it to point to anything.

I have been using std::make_shared((int*)1, [](auto) { /* do stuff */ }), but I really don't need the int. Maybe I'm missing something, but I see overly-verbose boilerplate all over the place for doing precisely this.

CodePudding user response:

How about this? Same use of a shared_ptr that doesn't point to anything but with a custom constructor that takes any function (with no arguments).

class shared_destructible : public std::shared_ptr<void*> {
public:
    template<typename F, typename = std::enable_if_t<std::is_invokable_v<F>>>
    shared_destructible(F f): std::shared_ptr<void*>(nullptr, [f](void*){
        f();
    }) {}
}

Example use

int main() {
    int test = 2023;
    shared_destructible a([test]() { std::cout << test << std::endl; });
    auto b = a;
    auto c = a;
    return 0;
}

Output:

2023

CodePudding user response:

std::shared_ptr can give you the "shared" part, and you can write your own custom class for the destruction part. In full generality (if you want the lambda parameter like in your example),

class Destructible {
private:
  std::function<void()> impl;
public:
  Destructible(const std::function<void()>& impl) : impl(impl) {}
  ~Destructible() {
    impl();
  }
};

Then the type you're looking for is called std::shared_ptr<Destructible>. You can construct one with std::make_shared<Destructible>([]() { ... });

  • Related