Initialize unique_ptr element to empty

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; } } 
+6
source share
2 answers

Your mistake:

 void setActor(Actor *actor) { actor = std::move(actor); }; 

You assign the result std::move parameter actor . You probably meant reset actor member variable with the actor parameter:

 void setActor(Actor *actor) { this->actor.reset(actor); }; 

As an additional note, you can simply change your constructor to this:

 Position::Position(int x, int y) : x(x), y(y) { } 

This initializes the x and y members with arguments, and default-initialize std::unique_ptr<Actor> actor is null.

+5
source

You do not need to initialize the std :: unique pointer to null. Just leave this as the default empty value in the constructor and only when reset points to a non-zero pointer.

+4
source

Source: https://habr.com/ru/post/983141/


All Articles