为什么没有针对 std::shared_ptr<T[]> 的专业化?
Why is there no specialisation for std::shared_ptr<T[]>?
我想知道为什么动态数组由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[]
。
相关文章:
- 如何使用默认参数等选择模板专业化
- 模板化建造师专业化
- 类模板的成员功能的定义在单独的TU中完全专业化
- EASTL矢量<向量<int>>连续的
- 部分专业化和嵌套模板
- 模板专业化可以进入我的.cpp吗?
- 别名模板的专业化 C++11 中没有开销的最佳替代方案
- 部分专业化和对标准::void_t<>的需求
- "专业化不参与超载"
- 特定好友功能专业化
- 是否可以混合使用SFINAE和模板专业化?
- 为什么在班级专业化上会出现错误?
- enable_if如何帮助选择类模板的专业化?
- std::initializer_list可以专业化吗?
- 派生类中纯虚拟基方法的专业化
- "expected a '>'"类模板专业化?
- Clang不会编译GCC会编译的模板专业化
- 我可以用clang AST从模板专业化中获得默认的模板参数吗
- 函数模板部分专业化-有什么解决方法吗
- 明确的专业化“ CheckIntmap&lt;&gt;”实例化