Thomas Thomas - 4 days ago 5
C++ Question

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

qxz qxz
Answer

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 n, std::unique_ptr<int[]>(nullptr)). Note that this creates a temporary instance of std::unique_ptr, implicitly converted/constructed from your nullptr argument. That constructor of vector is supposed to copy the value you pass 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.

Comments