为什么没有[]操作符用于std :: shared_ptr? [英] Why is there no [] operator for std::shared_ptr?

查看:74
本文介绍了为什么没有[]操作符用于std :: shared_ptr?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道这个事实背后的原因是, std :: shared_ptr 没有定义 [] 数组运算符。特别是为什么 std :: unique_ptr 具有此运算符而不具有 std :: shared_ptr 的功能?

I wonder what the rationale is behind the fact, that std::shared_ptr does not define the [] operator for arrays. In particular why does std::unique_ptr feature this operator but not std::shared_ptr?

推荐答案

std :: unique_ptr 仅定义 operator [] 在数组的特殊化中: std :: unique_ptr< T []> 。对于非数组指针,operator []仍然没有多大意义(仅 [0] )。

std::unique_ptr only defines operator[] in a specialization for arrays: std::unique_ptr<T[]>. For non-array pointers, the operator[] doesn't make much sense anyways (only [0]).

缺少这样的对 std :: shared_ptr 的专业化(在C ++ 11中),相关问题对此进行了讨论:为什么没有std :: shared_ptr< T []

Such a specialization for std::shared_ptr is missing (in C++11), which is discussed in the related question: Why isn't there a std::shared_ptr<T[]> specialisation?

除非您提供自定义删除器,否则不应使用非数组智能指针进行数组分配。特别地, unique_ptr< int> p = new int [10] 不好,因为它调用 delete 而不是 delete [] 。使用 unique_ptr< int []> 代替,它调用 delete [] 。 (并且这实现了 operator [] )。如果您使用 shared_ptr 来保存 T [] ,则需要使用自定义删除器。另请参见 shared_ptr到数组:应该使用它吗?-但它不提供 operator [] ,因为它使用类型擦除来区分数组和非数组(智能指针类型独立于提供的指针

You should not use a non-array smart pointer with array allocation, unless you provide a custom deleter. In particular, unique_ptr<int> p = new int[10] is bad, since it calls delete instead of delete[]. Use unique_ptr<int[]> instead, which calls delete[]. (And this one implements operator[]). If you're using shared_ptr to hold a T[], you need to use a custom deleter. See also shared_ptr to an array : should it be used? -- but it doesn't provide operator[], since it uses type erasure to distinguish between array and non-array (the smart pointer type is independent of the provided deleter).

如果您想知道为什么数组没有 shared_ptr 专业化:那是一个建议,但当时不包含在标准中(主要是因为您可以通过为 ptr [i] <编写 ptr.get()+ i 来解决/ code> )。

If you wonder why there is no shared_ptr specialization for arrays: that was a proposal, but wasn't included in the standard (mainly since you can work around by writing ptr.get() + i for ptr[i]).

这篇关于为什么没有[]操作符用于std :: shared_ptr?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆