Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there no specialisation for std::shared_ptr<T[]>?

Tags:

c++

c++11

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?

like image 903
Vahid Noormofidi Avatar asked Sep 22 '15 22:09

Vahid Noormofidi


1 Answers

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[].

like image 106
Cheers and hth. - Alf Avatar answered Sep 28 '22 13:09

Cheers and hth. - Alf