为什么没有针对 std::shared_ptr<T[]> 的专业化?

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

本文关键字:专业化 gt lt ptr std shared 为什么      更新时间:2023-10-16

我想知道为什么动态数组由std::unique_ptr<>直接支持,而不是由std::shared_ptr<>:

unique_ptr<int[]> ptr1(new int[n]); /// OK!
shared_ptr<int[]> ptr2(new int[n]); /// Incorrect: will not call delete[]

更新:我发现第二行可以重写为:

 shared_ptr<int> ptr2(new int[n], default_delete<int[]>());

现在我想知道幕后发生了什么,使std::shared_ptr与第二种方法一起工作,而不是以类似于std::unique_ptr的方式?

对于shared_ptr,如果您使用new[]分配数组,则必须使用调用delete[]的自定义删除器。

同样,您必须小心向上和向下转换,就像使用原始指针一样,以免调用未定义行为。

unique_ptr直接支持数组,所以当它知道它持有一个指向数组的指针时,你不能向上或向下强制转换,默认的删除器调用delete[]