std::unique_ptr
支持数组,例如:
std::unique_ptr<int[]> p(new int[10]);
但这是必要的吗?也许使用std::vector
或std::array
更方便。
你觉得这个结构有什么用处吗?
发布于 2014-07-21 01:19:30
您可能使用unique_ptr
的一个原因是,如果您不想支付value-initializing数组的运行时成本。
std::vector<char> vec(1000000); // allocates AND value-initializes 1000000 chars
std::unique_ptr<char[]> p(new char[1000000]); // allocates storage for 1000000 chars
std::vector
构造函数和std::vector::resize()
将对T
进行赋值初始化--但是如果T
是一个POD,new
就不会这样做。
请参阅Value-Initialized Objects in C++11 and std::vector constructor
注意,在这里vector::reserve
不是可选的:Is accessing the raw pointer after std::vector::reserve safe?
这也是C程序员可能会选择malloc
而不是calloc
的原因。
发布于 2013-05-23 18:40:39
std::vector
可以被复制,而unique_ptr<int[]>
允许表示对数组的唯一所有权。另一方面,std::array
要求在编译时确定大小,这在某些情况下可能是不可能的。
发布于 2015-08-27 02:14:42
与std::vector
和std::array
相反,std::unique_ptr
可以拥有空指针。
当使用需要数组或NULL的C API时,这很方便:
void legacy_func(const int *array_or_null);
void some_func() {
std::unique_ptr<int[]> ptr;
if (some_condition) {
ptr.reset(new int[10]);
}
legacy_func(ptr.get());
}
https://stackoverflow.com/questions/16711697
复制相似问题