带向量的unique_ptr:错误:调用XXX的隐式删除副本构造函数 [英] unique_ptr with vector: error: call to implicitly-deleted copy constructor of XXX

查看:80
本文介绍了带向量的unique_ptr:错误:调用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:

错误:调用'std :: __ 1 :: unique_ptr<int [],std :: __ 1 :: default_delete<int []>>'

error: call to implicitly-deleted copy constructor of 'std::__1::unique_ptr< int [], std::__1::default_delete< int []> >'

推荐答案

我相信问题出在您的 vector 构造函数调用( 2:填充构造函数):

I believe the issue is with your vector constructor call (2: fill constructor):

std::vector<std::unique_ptr<int []>> vec(5, nullptr);

在这里,您实际上是在调用 vector(size_t(5),std :: unique_ptr< int []>(nullptr)).请注意,这将创建一个 std :: unique_ptr 的临时实例,该实例从您的 nullptr 参数隐式转换/构造.然后, vector 构造函数将复制您传递给它的该值 n 次以填充容器;由于您无法复制任何 unique_ptr (甚至是null),因此会从该构造函数的代码中得到编译器错误.

Here, you're essentially calling 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. The vector constructor is then supposed to copy this value you pass to it n times to fill out the container; since you can't copy any unique_ptr (even a null one), you get your compiler error from within that constructor's code.

如果您要立即替换那些初始的 nullptr 值,则应该只构造一个空的 vector push_back 您的新元素:

If you're immediately replacing those initial nullptr values, you should just construct an empty vector and push_back your new elements:

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)
...

要使用一定数量的空值初始化 vector ,请省略第二个参数:

To initialize a vector with some number of null values, omit the second parameter:

std::vector<std::unique_ptr<int []>> vec(5);

这将使用默认构造函数构造每个 unique_ptr ,不需要任何复制.

This will construct each unique_ptr with the default constructor, not requiring any copying.

这篇关于带向量的unique_ptr:错误:调用XXX的隐式删除副本构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆