Re: Different syntax for shared arrays between unique_ptr and
shared_ptr
On 15 Apr., 08:29, Edward Diener wrote:
As I understand it specifying a non-shared array with unique_ptr is
done using the syntax:
std::unique_ptr<T[]> up(new T[n]);
The unique_ptr has a partial specialization to handle this.
The syntax for handling shared arrays with shared_ptr is different:
std::shared_ptr<T> sp(new T[n],std::default_delete<T[]>());
Why is the syntax for working with arrays in unique_ptr and shared_ptr
different ?
The short and easy answer: because nobody proposed to add a T[]
specialization to shared_ptr (not to my knowledge).
I just want to point out that shared_ptr needs more book keeping
(reference counter). So, you'd have two allocated memory blocks, the
ref counter and the array itself. This memory layout is very similar
to the layout you get by writing
auto sv = make_shared<vector<T>>(n);
on any decent implementation that would allocate the sizeof(vector<T>)
bytes together with the ref counting book keeping bits. You're just
getting an an additional level of indirection if you access vector
elements via sv. Though, You can avoid this using the vector's
iterators for a loop. So, what I'm saying is that I see little reason
to prefer sharedptr<T> with an array deleter over a
shared_ptr<vector<T>>.
Cheers!
SG
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]