[英]unique_ptr with vector: error: call to implicitly-deleted copy constructor of XXX
I want to manage a two dimensional array as below: 我要管理一个二维数组,如下所示:
std::vector<std::unique_ptr<int []>> vec(5, nullptr);
vec[0] = std::make_unique<int []>(3);
vec[1] = std::make_unique<int []>(4);
...
However I get an error: 但是我得到一个错误:
error: call to implicitly-deleted copy constructor of 'std::__1::unique_ptr< int [], std::__1::default_delete< int []> >'
错误:调用“ std :: __ 1 :: unique_ptr <int [],std :: __ 1 :: default_delete <int []>>”的隐式删除副本构造函数
I believe the issue is with your vector
constructor call ( 2: fill constructor ): 我相信问题出在您的
vector
构造函数调用 ( 2:填充构造函数 )上:
std::vector<std::unique_ptr<int []>> vec(5, nullptr);
Here, you're essentially calling vector(size_t(5), std::unique_ptr<int[]>(nullptr))
. 在这里,您实际上是在调用
vector(size_t(5), std::unique_ptr<int[]>(nullptr))
。 Note that this creates a temporary instance of std::unique_ptr
, implicitly converted/constructed from your nullptr
argument. 请注意,这会创建一个
std::unique_ptr
的临时实例,该实例从您的nullptr
参数隐式转换/构造。 The vector
constructor is then supposed to copy this value you pass to it n
times to fill out the container; 然后,
vector
构造函数将复制您传递给它的该值n
次以填充容器。 since you can't copy any unique_ptr
(even a null one), you get your compiler error from within that constructor's code. 由于您无法复制任何
unique_ptr
(甚至是null),因此会从该构造函数的代码中获取编译器错误。
If you're immediately replacing those initial nullptr
values, you should just construct an empty vector
and push_back
your new elements: 如果您要立即替换这些初始的
nullptr
值,则应仅构造一个空vector
并将新元素push_back
:
std::vector<std::unique_ptr<int []>> vec; // default constructor
vec.push_back(std::make_unique<int []>(3)); // push the elements (only uses the move
vec.push_back(std::make_unique<int []>(4)); // constructor of the temporary)
...
To initialize a vector
with some number of null values, omit the second parameter: 要使用一定数量的空值初始化
vector
,请省略第二个参数:
std::vector<std::unique_ptr<int []>> vec(5);
This will construct each unique_ptr
with the default constructor , not requiring any copying. 这将使用默认构造函数构造每个
unique_ptr
,而不需要任何复制。
std::vector<std::unique_ptr<int []>> vec(5, nullptr);
This line copy construct 5 std::unique_ptr<int []>
from a temporary constructed from nullptr
. 该行从
nullptr
构造的临时副本中构造5 std::unique_ptr<int []>
。 It's illegal. 是非法的
I think you want this: 我想你想要这个:
std::vector<std::unique_ptr<int []>> vec;
vec.reserve(5);
vec.push_back(std::make_unique<int []>(std::size_t(3)));
If you really want a vector with 5 nullptr, here is the solution: 如果您真的想要一个带有5个nullptr的向量,请使用以下解决方案:
std::vector<std::unique_ptr<int []>> vec(5);
vec[0] = std::make_unique<int []>(std::size_t(3));
您将在期望的数组中插入整数元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.