Search code examples
c++arraysshared-ptr

shared_ptr<> to an array custom deleter (with make_shared)


Is it possible to use make_shared and a custom deleter for an array that a shared_ptr<> points to (below is the way I tried doing it via the constructor, but I have no idea how that would work via using make_shared)?

int n = 5;
shared_ptr<int> a(new int[n], default_delete<int[]>());

What I would like to make it look like is something similar to this, but with allocating memory for an int array and also having a custom deleter. Is that possible?

int n = 5;
shared_ptr<int> a;
a = make_shared<int>();

Solution

  • Unfortunately there is no way to specify a custom deleter as of right now with std::make_shared, you could however, make a wrapper around make_shared if you want

    (a little less efficient, but ¯\_(ツ)_/¯)

    template <typename Type, typename Deleter, typename... Args>
    auto make_shared_deleter(Deleter&& deleter, Args&&... args) {
        auto u_ptr = std::make_unique<Type>(std::forward<Args>(args)...);
        auto with_deleter = std::shared_ptr<Type>{
            u_ptr.release(), std::forward<Deleter>(deleter)};
        return with_deleter;
    }
    

    And then use it like so

    int main() {
        auto ptr = make_shared_deleter<int>(std::default_delete<int>(), 1);
        cout << *ptr << endl;
    }
    

    If you just want to use a shared_ptr and have it point to an array, see shared_ptr to an array : should it be used? for more