我想知道为什么动态数组直接支持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[]
Run Code Online (Sandbox Code Playgroud)
更新:我发现第二行可以改写为:
shared_ptr<int> ptr2(new int[n], default_delete<int[]>());
Run Code Online (Sandbox Code Playgroud)
现在我想知道幕后发生了什么,这使得std::shared_ptr采用第二种方法而不是类似的方式std::unique_ptr?
如果您使用 分配数组,则shared_ptr必须使用调用 的自定义删除器。delete[]new[]
此外,您必须像处理原始指针一样小心向上和向下转换,以免调用未定义的行为。
unique_ptr直接支持数组,因此当它知道它持有指向数组的指针时,您无法向上或向下转换,并且默认删除器会调用delete[].