简体   繁体   中英

Instances of the same object in C++ (game programming)

I was wondering how to create multiple instances of the same object in C++. I have an example. Let's say I am creating a simple action game and I have an object called "Bullet". If I hit fe a CTRL key it causes a gunfire. So I create an instance of Bullet. The instance dies when the bullet hits something or get out of the window. But what if I have fe something like machine gun. It can fire many bullets in a row. So I have to create many instances of Bullet, but how can I do that? Should I at the beginning make a pointer like this

Bullet *pointer;

Then when I want to create an instance of the bullet I allocate a space in memory for one "bullet". And when I want to create next bullet I allocate more space and so on. But when a bullet "dies" I got a dead space in memory...

So I do not know how to handle this situation. I am new to OOP. I have programmed in C and now I want to learn C++ through the game programming (it is quite fun) :-). Thanks for the answers!

Simply use std::vector<Bullet> bullets to store all of your bullets. You are going to need all those objects anyway and std::vector will:

  • amortize appending new objects
  • allow you to shrink_to_fit if at any point the vector became too large
  • allow you to reserve a certain number of elements at the beginning, effectively creating an empty pool of objects
  • keep all your objects contiguously, making everything very efficient

You may also want to try std::unordered_map which has almost constant time insertion and removal.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM