Std::unique_ptr支持数组,例如:

std::unique_ptr<int[]> p(new int[10]);

但这是必要的吗?可能使用std::vector或std::array更方便。

你觉得这个结构有什么用处吗?


当前回答

I have used unique_ptr<char[]> to implement a preallocated memory pools used in a game engine. The idea is to provide preallocated memory pools used instead of dynamic allocations for returning collision requests results and other stuff like particle physics without having to allocate / free memory at each frame. It's pretty convenient for this kind of scenarios where you need memory pools to allocate objects with limited life time (typically one, 2 or 3 frames) that do not require destruction logic (only memory deallocation).

其他回答

std::vector可以被复制,而unique_ptr<int[]>允许表示数组的唯一所有权。另一方面,Std::array要求在编译时确定大小,这在某些情况下可能是不可能的。

有些人无法奢侈地使用std::vector,即使是使用分配器。有些人需要一个动态大小的数组,所以std::array已经失效。有些人从已知返回数组的代码中获取数组;这段代码不会被重写为返回一个向量或其他东西。

通过允许unique_ptr<T[]>,您可以满足这些需求。

简而言之,您可以在需要时使用unique_ptr<T[]>。当其他选择都不适合你的时候。这是最后的手段。

I have used unique_ptr<char[]> to implement a preallocated memory pools used in a game engine. The idea is to provide preallocated memory pools used instead of dynamic allocations for returning collision requests results and other stuff like particle physics without having to allocate / free memory at each frame. It's pretty convenient for this kind of scenarios where you need memory pools to allocate objects with limited life time (typically one, 2 or 3 frames) that do not require destruction logic (only memory deallocation).

这里有权衡,您可以选择与您想要的匹配的解决方案。我能想到的是:

初始大小

vector和unique_ptr<T[]>允许在运行时指定大小 数组只允许在编译时指定大小

调整

array和unique_ptr<T[]>不允许调整大小 向量是

存储

vector和unique_ptr<T[]>将数据存储在对象之外(通常在堆上) 数组将数据直接存储在对象中

复制

数组和向量允许复制 unique_ptr<T[]>不允许复制

交换/移动

vector和unique_ptr<T[]>有O(1)次交换和移动操作 数组有O(n)次交换和移动操作,其中n是数组中元素的数量

指针/引用/迭代器失效

array ensures pointers, references and iterators will never be invalidated while the object is live, even on swap() unique_ptr<T[]> has no iterators; pointers and references are only invalidated by swap() while the object is live. (After swapping, pointers point into to the array that you swapped with, so they're still "valid" in that sense.) vector may invalidate pointers, references and iterators on any reallocation (and provides some guarantees that reallocation can only happen on certain operations).

概念和算法的兼容性

array和vector都是容器 unique_ptr<T[]>不是容器

我不得不承认,对于基于策略的设计来说,这似乎是一个重构的机会。

为了回答人们认为你“必须”使用vector而不是unique_ptr,我在GPU上的CUDA编程中有一个案例,当你在Device中分配内存时,你必须使用一个指针数组(使用cudaMalloc)。 然后,当在Host中检索该数据时,必须再次寻找指针,unique_ptr可以很容易地处理指针。 将double*转换为vector<double>的额外成本是不必要的,并且会导致性能损失。