aspose file tools*
The moose likes Other Languages and the fly likes Vectors, Allegro, and Destructors, oh my! Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Languages » Other Languages
Bookmark "Vectors, Allegro, and Destructors, oh my!" Watch "Vectors, Allegro, and Destructors, oh my!" New topic
Author

Vectors, Allegro, and Destructors, oh my!

Wes McClintock
Greenhorn

Joined: Jul 19, 2011
Posts: 25
Alright, so I'm using the Allegro gaming library in C++ to make a little space shooter game, and need some help with the bullets.

in semi-psuedocode its works like this:


now, all this works fine, but the problem is that when a laser is off the screen, it's still taking up memory, and space in the vector object (and therefore adding to the length of the draw method). Ideally, I would like to remove the laser object from the vector, and then destruct (if destruct isn't what I'm looking for, I just want to delete the object) it.

I'll go try and answer some questions now so I don't feel leechy, thanks.
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3649
    
  17

Why not just give the laser a 'time to live', and when it has expired, remove and destruct it?
Wes McClintock
Greenhorn

Joined: Jul 19, 2011
Posts: 25
Stephan van Hulst wrote:Why not just give the laser a 'time to live', and when it has expired, remove and destruct it?


Because then it would still be in the vector wouldn't it? and since every object in the vector adds another iteration to the for loop. Also, I'm not really sure how to use destructors, I couldn't find any good guides. Can you just call ~lasers() (which is blank) and be done with it?

Sorry, as I said I'm very new too C++.
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3649
    
  17

No, that's why I also used the word "remove" :P

I take it you're using an iterator to go over all the elements when you want to draw them or update their positions or whatever. Before you do, inspect their time to live field, and if the laser has expired, call the erase method on the container, and then destruct the laser itself. You should probably use a list<laser> instead of a vector<laser>, because a list should be faster at removing elements at some random position.

The loop would look something like this:
Note that I've hardly ever coded in C++ myself, so I can't guarantee this will work.

[edit]

I figured the destructor is not necessary, because C++ automatically destroys objects in certain circumstances, I believe. I changed the code accordingly.
Wes McClintock
Greenhorn

Joined: Jul 19, 2011
Posts: 25
Thanks, you guys are always so helpful.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Vectors, Allegro, and Destructors, oh my!