In my program, I have a bunch of custom class Position objects. The position announcement is as follows:
class Position { public: Position(int x, int y); ~Position(); Actor *getActor() { return actor.get(); }; void setActor(Actor *actor) { actor = std::move(actor); }; Actor *clearActor() { return actor.release(); }; int getX() { return x; }; int getY() { return y; }; private: int x, y; std::unique_ptr<Actor> actor; };
I also have a class called Actor. Not every position will have an Actor, and therefore most of the time the unique_ptr "actor" of the Position object must be empty (I use unique_ptrs to automatically clear any actor associated with the Position at runtime).
The Position constructor is as follows:
Position::Position(int x, int y) { this->x = x; this->y = y; actor.reset(nullptr); }
However, I know that this incorrectly sets the stored pointer to nullptr, because when I try to call actor.get () inside Position :: getActor (), I get the error message as follows:
The exception for the first chance is 0x01096486 at ____. exe: 0xC0000005: read access violation location 0x00000008.
Is there a way to initialize a unique_ptr element to nullptr? I know I can get around this by adding a variable to the Actor class, which determines whether the Actor is active or not, setting unique_ptr for the new inactive Actor and ignoring all inactive Actors, but I would prefer to avoid this if possible.
Thanks!
Edit: I added code where I call getActor:
bool Grid::addActor(Actor *actor, int x, int y) { Position *destination = at(x, y); if (!destination->getActor()) { destination->setActor(actor); actor->setPosition(x, y); actor->setGrid(this); return true; } else { inactive_actors.emplace_back(actor); return false; } }