unique_ptr with vector: error: call to implicitly-deleted copy constructor of XXX

落花浮王杯 提交于 2019-12-13 15:24:57

问题


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 []> >'


回答1:


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

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

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.

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

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

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

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




回答2:


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

This line copy construct 5 std::unique_ptr<int []> from a temporary constructed from nullptr. 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:

std::vector<std::unique_ptr<int []>> vec(5);
vec[0] = std::make_unique<int []>(std::size_t(3));



回答3:


You are inserting integer elements where is expected array.



来源:https://stackoverflow.com/questions/40878530/unique-ptr-with-vector-error-call-to-implicitly-deleted-copy-constructor-of-xx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!