简体   繁体   中英

C++ list - add items

I'm new to C++ and have a problem using list. I can't understand why i'm getting an error in the example bellow.

GameObject class is an abstract class Player class and Bullet class inherit GameObject class

list<GameObject*> gameObjects = list<GameObject*>();
gameObjects.push_front(&player);
while(gameLoop)
{
    if (canShoot)
    {
        Bullet b = Bullet(player.Position.X , player.Position.Y);
        gameObjects.push_front(&b);
    }   
    for each (GameObject *obj in gameObjects)
    {
        (*obj).Update(); // get an error
    }
}

The error is Debug Error -Abort() Has Been Called.

Your foreach syntax is just wrong, and actually, more is, to loop over every element in the list make it:

for (GameObject *obj : gameObjects)
{
   obj->Update(); 
}

Or, pre C++11:

for(std::list<GameObject*>::iterator itr = gameObjects.begin(); itr != gameObjects.end(); ++itr)
{
  (*itr)->Update();
}

Also, you are creating a Bullet object in the scope of if (canShoot) and push it's address to the std::list<GameObject*> . By the time you reach your foreach the Bullet object will already have been destroyed and thus your pointers in the list are dangling.

Dynamically allocate your objects on the heap:

list<GameObject*> gameObjects;

while(gameLoop)
{
    if (canShoot)
    {
        Bullet* b = new Bullet(player.Position.X , player.Position.Y);
        gameObjects.push_front(b);
    }   
    for (GameObject* obj : gameObjects)
    {
        obj->Update();
    }
}

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