Reputation: 12431
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 []> >'
Upvotes: 2
Views: 5175
Reputation: 3864
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.
Upvotes: 6
Reputation: 6016
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));
Upvotes: 2