gpt4 book ai didi

c++ - 为什么 std::unique_ptr 需要专门用于动态数组?

转载 作者:太空狗 更新时间:2023-10-29 21:20:32 25 4
gpt4 key购买 nike

我检查了 VC++ 2013 和 clang 3.4,发现它们都实现了 std::unique_ptr如下:

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能够判断 T 是否为数组类型。所以std::unique_ptr不需要专门处理数组情况。此外,我找不到 class unique_ptr 之间有任何实质性差异。和专门的class unique_ptr<T[], DeleterType> ,这是为什么呢?

最佳答案

不同之处在于构造函数和 reset() - unique_ptr<T>接受任何 X*可转换为 T* , 而 unique_ptr<T[]>只接受 T* .鉴于数组的语义和限制,这是有道理的。

此外,unique_ptr<T[]>重载 operator[] , 而 unique_ptr<T>没有。

关于c++ - 为什么 std::unique_ptr 需要专门用于动态数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24365250/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com