Evan Ward
Evan Ward

Reputation: 1429

c++ - managing entities in a vector

I have a std::vector<Enemy> enemies. At the end of the constructor of the Enemy class I do enemies.push_back(*this), although I'm not really sure this is the best way, or really why I need the pointer besides that I get an error without it.

During the destructor, i'd like to do something like:

enemies.erase(std::find(enemies.begin(), enemies.end(), *this));

But that doesn't really work out too well.

Basically, when an Enemy is instantiated I'd like it to go into the enemies vector, and when destroyed, removed.

Upvotes: 1

Views: 487

Answers (2)

outlyer
outlyer

Reputation: 3943

The vector stores copies of the objects, so the push_back() stores a copy (it doesn't enter a loop of constructors only because it uses the default copy constructor to create that copy, which won't do a second push_back), which means you're inadvertently duplicating objects, so it won't behave as expected.

Also

At the end of the constructor of the Enemy class I do enemies.push_back(*this), although I'm not really sure this is the best way, or really why I need the pointer besides that I get an error without it.

this is a pointer to that Enemy
*this is a reference to that Enemy

You can't add this to the vector because it's a pointer and your vector is not comprised of pointers.

Upvotes: 1

KalyanS
KalyanS

Reputation: 527

You may have to refine the question a bit more: What is the scope of std::vector enemies?

To answer the first part of the question: enemies has been declared to be a vector and not a pointer to Enemy. This is why you have to generate a reference by doing "*this" as an argument to push_back() call. You are effectively keeping a copy of all the objects constructed in this vector.

Is that your intent or do you mean it to be a registry of some kind, that is keeping track of all the Enemy objects created? If it is a registry that you want:

please use std::vector<Enemy*> enemies.

Please try to be specific about "doesn't really work out too well".

I think people can give better answers, if you give a bit more context.

Upvotes: 1

Related Questions