Reputation: 2633
I have searched for hours for a solution and tried different methods to address my compilation errors related to unique_ptr
and no copy/no assign. I even wrote a hidden copy and assign to prevent vector from calling it to no avail.
Here is the code causing the compilation errors:
class World{
World(const World&) {}
World& operator=(const World&) {return *this; }
std::vector<std::vector<std::unique_ptr<Organism>>> cell_grid;
public:
World() {
cell_grid = std::vector<std::vector<std::unique_ptr<Organism>>> (20, std::vector<std::unique_ptr<Organism>> (20, nullptr));
}
~World() {}
};
Compilation errors are related to the private member access issue.
Upvotes: 2
Views: 1538
Reputation: 219488
The problem is the use of this vector
constructor:
vector(size_type n, const T& value);
This constructor creates a vector
of length n
and each of the n
elements has a copy of value
. Since unique_ptr
can not be copied (and neither can a vector<unique_ptr>
), one can not use this constructor. Instead do this:
World()
: cell_grid(20)
{
for (auto& row : cell_grid)
row.resize(20);
}
The first line calls the default constructor of vector<unique_ptr>
, creating 20 size 0 vector<unique_ptr>
s.
The loop then resizes each of those vector<unique_ptr>
s to have size == 20, with each element being a default constructed unique_ptr
(which will have the value nullptr
).
Upvotes: 3