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>();
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With