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

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

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

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


当前回答

Scott Meyers在《Effective Modern c++》中这样说

对于数组来说,是否存在std::unique_ptr应该只对你的智力感兴趣,因为std::array, Std::vector, Std::string实际上总是比原始数组更好的数据结构选择。关于我能想到的唯一情况,当std::unique_ptr<T[]>有意义时,当你使用一个类似c的API,返回一个原始指针指向你假定拥有的堆数组时。

我认为Charles Salvia的答案是相关的:std::unique_ptr<T[]>是初始化一个在编译时不知道大小的空数组的唯一方法。对于使用std::unique_ptr<T[]>的动机,Scott Meyers会说些什么呢?

其他回答

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

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

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

我遇到了一个情况,我必须使用std::unique_ptr<bool[]>,它位于HDF5库(用于高效二进制数据存储的库,在科学中使用很多)中。一些编译器(在我的例子中是Visual Studio 2015)提供std::vector<bool>的压缩(通过在每个字节中使用8个bool),这对于HDF5之类的东西来说是一个灾难,它不关心这种压缩。对于std::vector<bool>, HDF5最终会因为压缩而读取垃圾。

猜猜谁在那里进行救援,在std::vector不起作用的情况下,我需要干净地分配一个动态数组?: -)

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

初始大小

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[]>不是容器

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

简而言之:它是迄今为止最节省内存的。

A std::string comes with a pointer, a length, and a "short-string-optimization" buffer. But my situation is I need to store a string that is almost always empty, in a structure that I have hundreds of thousands of. In C, I would just use char *, and it would be null most of the time. Which works for C++, too, except that a char * has no destructor, and doesn't know to delete itself. By contrast, a std::unique_ptr<char[]> will delete itself when it goes out of scope. An empty std::string takes up 32 bytes, but an empty std::unique_ptr<char[]> takes up 8 bytes, that is, exactly the size of its pointer.

最大的缺点是,每次我想知道字符串的长度,我必须调用strlen。

医生:这是穷人的性病。

让我们把std::unique_ptr<T[]>看作一个容器。实际上,由于缺少size字段,不能直接作为容器使用,它在标准库中可用的容器的“参数空间”中占据了一个点,而这个点不被其他合适的容器共享——即使在混合中添加Boost也不行。

如果你看看我对广泛可用的类向量/连续容器的比较,并寻找与std::unique_ptr相同的特性:

堆上的分配 容量在编译时不固定 在建造后不能改变容量(没有完全清理集装箱)

你会发现除了std::dynarray,没有其他容器提供所有这些;但它实际上不在标准库中——它本应被纳入c++ 14,但最终被拒绝了。

我不仅仅是在猜测。甚至在《SO》中,人们也偶尔这样描述事物;参见@KerrekSB 2013年对这个问题的回答。