I was wondering why dynamic arrays are directly supported by std::unique_ptr<>
but not by std::shared_ptr<>
:
unique_ptr<int[]> ptr1(new int[n]); /// OK!
shared_ptr<int[]> ptr2(new int[n]); /// Incorrect: will not call delete[]
Update: I found out that the second line can be rewritten as:
shared_ptr<int> ptr2(new int[n], default_delete<int[]>());
Now I am wondering what's going on behind the scene that makes std::shared_ptr
works with the second approach and not in the way similar to std::unique_ptr
?
With shared_ptr
you have to use a custom deleter that invokes delete[]
, if you allocate the array with new[]
.
Also, you have to be careful with up- and down-casting just as with raw pointers, so as not to invoke Undefined Behavior.
unique_ptr
has direct support for arrays, so that when it knows that it holds a pointer to array you can't up- or down-cast, and the default deleter invokes delete[]
.
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