Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I prevent adding an object in multiple vectors?

There are some objects that are Drawable and some that are Movable.
All movable objects are dawable.
I store all the drawable objects in a vector called drawables and movable objects in a vector called movables. I also have vectors ships and bullets which contain objects of type Ship and Bullet respectively. Ship and Bullet both are Movable

Here's the structure of the classes:

class Drawable {
public:
    void draw();
};

class Movable : public Drawable {
public:
    void move();
}

class Ship : public Movable {
public:
    Ship();
}

class Bullet : public Movable {
public:
    Bullet();
}

The vectors are declared as follows:

std::vector<Drawable*> drawables;
std::vector<Movable*> movables;
std::vector<Ship*> ships;
std::vector<Bullet*> bullets;

The thing is, that each time I create a Ship I have to add it in all the vectors i.e.

drawables.push_back(ship);
movables.push_back(ship);
ships.push_back(ship);

I have created separate drawables and movables vectors since I have a draw() function which calls the draw() method of all objects in the drawables vector. Similarly, I have a move() function which calls the move() method of all objects in the movables vector.

My question is, how do I change the structure to prevent adding the same thing in different vectors. I also need to remove objects from all the vectors once it's purpose is done.
For example, once the bullet hits someone or moves out of the screen, then I'll have to remove it from the vectors drawables, movables and bullets after searching it in all three vectors.
It seems like I'm not using the correct approach for storing these objects. Please suggest an alternative.

This seems more like a software engineering question than a coding question. Please migrate the question to other forum if necessary.

like image 581
Mahesh Bansod Avatar asked Apr 02 '26 16:04

Mahesh Bansod


1 Answers

Assuming you are using a reasonably modern compiler, this is exactly why shared_ptr exists.

The problem is that you have no idea which vector owns the object, so you don't know which one to delete. shared_ptr takes are of this for you: it manages the lifetime of the object, and will delete it once the last reference to the object is destroyed.

To create a new Ship, you could do something like this:

auto ship = std::make_shared<Ship>();

drawables.push_back(ship);
movables.push_back(ship);
ships.push_back(ship);

At this point ship has 4 references (one for each vector, and the ship variable itself). It will automatically be deleted once it has been removed from all three vectors and the local variable goes out of scope.

like image 181
Andy Avatar answered Apr 04 '26 07:04

Andy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!