Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Vectors, Allegro, and Destructors, oh my!

 
Wes McClintock
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 6323
78
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why not just give the laser a 'time to live', and when it has expired, remove and destruct it?
 
Wes McClintock
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 6323
78
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, you guys are always so helpful.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic