7

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>();
TheDoomDestroyer
  • 2,434
  • 4
  • 24
  • 45
  • Possible duplicate of [shared\_ptr to an array : should it be used?](https://stackoverflow.com/questions/13061979/shared-ptr-to-an-array-should-it-be-used) – Sneftel Jul 08 '17 at 12:24
  • 1
    @Sneftel While the question there is similar, the one you linked does not comply with make_shared, which is the issue I got here. – TheDoomDestroyer Jul 08 '17 at 12:27

1 Answers1

7

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

Curious
  • 20,870
  • 8
  • 61
  • 146
  • 1
    Ah, I see. That helps a bit. Thank you for the reply. – TheDoomDestroyer Jul 08 '17 at 12:28
  • 1
    I mean, you don't *really* need `with_deleter` :) – Rakete1111 Jul 08 '17 at 12:31
  • But a big part of using `std::make_shared` is the reduction in allocations, this doesn't address that – Passer By Jul 08 '17 at 16:26
  • @PasserBy A big part of `std::make_shared` is also ensuring exception safety (as with `std::make_unique`). I already mentioned in my answer that the above is less efficient than `std::make_shared` because of the repeated allocation. – Curious Jul 08 '17 at 16:29
  • Exception safety issue is [resolved in C++17](https://stackoverflow.com/a/44932594/4832499). And for the efficiency part, it's not immediately apparent that what the problem is, maybe link to a post about that? – Passer By Jul 08 '17 at 16:41