jeudi 26 avril 2018

SDL2 framework crash when deleting pointer from std::vector while iterating

my SDL2 framework crashes when i delete a pointer for a upgrade from a std::vector containing pointers while iterating through them.

void MyScene::grabUpgrade()
{
std::vector<Upgrade_Base*>::iterator it = upgradeVector.begin();
while (it != upgradeVector.end()) {
    if (player->isColliding((*it))) {

        std::cout << player->health << std::endl;

        //using the upgrade
        (*it)->use(player);

        //removing the upgrade after being used
        this->removechild((*it));
        delete (*it);
        it = upgradeVector.erase(it);

        std::cout << player->health << std::endl;

    }
    else {
        it++;
    }
}
}

here you see the code i use to use and delete the upgrade, this code is being called through the update function.

the std::vector is declared private in the .h file of the scene, the code above is positioned in the .cpp file of the scene.

i already tested the isColliding function of the player and thats working perfectly normal so it has nothing to do with that atleast.

i am aware that this is a really basic question but for some reason this time i can't for my life figure out whats going wrong here.

Aucun commentaire:

Enregistrer un commentaire