Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does std::unique_ptr need to be specialized for dynamic arrays?

I examined VC++ 2013 and clang 3.4 and found that both implemented std::unique_ptr as follows:

template<class T, class DeleterType = std::default_delete<T>>
class unique_ptr
{
    // ...
};

template<class T, class DeleterType>
class unique_ptr<T[], DeleterType>
{
    // ...
};

std::default_delete is able to determine whether T is an array type. So std::unique_ptr needn't to specialize itself to handle array case. Moreover, I cannot find any substantial differences between class unique_ptr and the specialized class unique_ptr<T[], DeleterType>, why is it?

like image 430
xmllmx Avatar asked Dec 04 '25 15:12

xmllmx


1 Answers

The difference is in constructors and reset() - unique_ptr<T> accepts any X* convertible to T*, while unique_ptr<T[]> only accepts a T*. Which makes sense, given the semantics and restrictions of arrays.

Also, unique_ptr<T[]> overloads operator[], while unique_ptr<T> does not.

like image 137
Angew is no longer proud of SO Avatar answered Dec 07 '25 03:12

Angew is no longer proud of SO



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!