在unique_ptr中动态分配的数组上应用std::begin()

Apply std::begin() on an dynamically allocated array in a unique_ptr?

本文关键字:std 应用 begin 数组 unique ptr 动态分配      更新时间:2023-10-16

在动态分配的数组上有一个唯一的指针:

const int quantity = 6;
unique_ptr<int[]> numbers(new int[quantity]);
到目前为止,这应该是正确的(我认为,模板参数中的[]很重要,对吗?)顺便说一下:有可能像int some_array[quantity] = {};一样初始化元素吗?

现在我试着像这样遍历数组:

for (auto it = begin(numbers); it != end(numbers); ++it)
    cout << *it << endl;

但我不明白,语法是如何正确的。有办法吗?或者,我可以使用如下索引:

for (int i = 0; i < quantity; ++i)
    cout << numbers[i] << endl; 

是首选的吗?

(与标题不直接相关:作为下一步,我想将其减少到基于范围的for循环,但我现在只有VS2010,无法尝试。但是有什么我必须处理的吗?)

谢谢!Gerrit

编译器应该将此原型应用于std::begin:

template< class T, size_t N > 
T* begin( T (&array)[N] );

表示参数类型为int(&)[N],既不是std::unique_ptr,也不是int *。如果这是可能的,std::end如何计算最后一个?

但为什么不直接使用原始指针或STL容器?

const int quantity = 6;
std::unique_ptr<int[]> numbers{new int[quantity]};
// assignment
std::copy_n(numbers.get(), quantity,
            std::ostream_iterator<int>(std::cout, "n"));
const int quantity = 6;
std::vector<int> numbers(quantity, 0);
// assignment
std::copy(cbegin(numbers), cend(numbers),
          std::ostream_iterator<int>(std::cout, "n"));

c++中动态分配的数组(即:new []的结果)没有大小信息。因此,您无法获得数组的大小。

你可以这样实现std::begin:

namespace std
{
  template<typename T> T* begin(const std::unique_ptr<T[]> ptr) {return ptr.get();}
}

但是没有办法实现end

你考虑过使用std::vector吗?有了移动支持,它应该不会比一个unique_ptr到一个数组更昂贵。