I have a class Grid declared as follows:
class Grid
{
public:
Grid(int length_x, int length_y);
~Grid();
Position *at(int x, int y);
private:
int length_x, length_y;
std::vector<std::unique_ptr<Position>> grid;
};
Its most important member variable is the vector of unique_ptr<Position>
, which I'm using to simulate a 2-dimensional array whose size is determined at runtime. The class declaration for the Position is as follows:
class Position {
public:
Position(int x, int y);
~Position();
int getX() { return x; };
int getY() { return y; };
private:
int x, y;
};
In the Grid's constructor, I want to create the desired number of Positions and add them to the vector<unique_ptr<Position>
. Here's what I've tried so far:
Grid::Grid(int length_x, int length_y)
: length_x(length_x), length_y(length_y)
{
grid.resize(length_x * length_y);
for (int x = 0; x < length_x; x++) {
for (int y = 0; y < length_y; y++) {
std::unique_ptr<Position> temp = std::make_unique<Position>(x, y);
grid.push_back(std::move(temp));
}
}
}
I've also tried using emplace_back()
instead of push_back()
, as well as replacing the lines inside the for-loop with
grid.push_back(std::make_unique<Position>(x, y));
and also
grid.emplace_back(std::make_unique<Position>(x, y));
Nothing has worked, because when I try accessing any of the Positions' coordinates by iterating through the vector and calling Position::toString(), I always get the following error:
First-chance exception at 0x0087D8A3 in CombatSim.exe: 0xC0000005: Access violation reading location 0x00000000. Unhandled exception at 0x0087D8A3 in CombatSim.exe: 0xC0000005: Access violation reading location 0x00000000.
As far as I know, I could have one of four problems:
1) I'm adding the unique_ptr to the created Position object to the vector incorrectly
2) I'm using the wrong method to dynamically create Position objects.
3) All of the above.
4) Something I don't know about.
Here's the rest of the code:
Position::Position(int x, int y)
: x(x), y(y)
{
}
std::string Position::toString()
{
std::string result = "Position at (" + std::to_string(x) + ", " + std::to_string(y) + ")";
return result;
}
Aucun commentaire:
Enregistrer un commentaire