简体   繁体   中英

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

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.

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

您将在期望的数组中插入整数元素。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM