Why is there no specialisation for std::shared
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[]
.
上一篇: 为什么传统C标识符不需要名称空间标准?