map迭代器擦除不调用适当的析构函数

pig*_*d10 1 c++ stdmap sfml

gameObjects是一个std::map<sf::String,VisibleGameObject*>,results是一个std::map<sf::String,VisibleGameObject*>::iterator.当这运行:

return gameObjects.erase(results);
Run Code Online (Sandbox Code Playgroud)

我期望VisibleGameObject的析构函数运行,这是:

VisibleGameObject::~VisibleGameObject(){
    m_pSceneManager->removeSprite(name);
}
Run Code Online (Sandbox Code Playgroud)

永远不会运行,直到持有的类gameObjects被销毁,然后运行:

GameObjectManager::~GameObjectManager(){
    std::for_each(gameObjects.begin(),gameObjects.end(),GameObjectDeallocator());
}

struct GameObjectDeallocator{
        void operator()(const std::pair<sf::String,VisibleGameObject*>&p) const{
            delete p.second;
        }
    };
Run Code Online (Sandbox Code Playgroud)

然后它确实运行.为什么不在第一种情况下运行?

使用SFML 2.0

谢谢

Fle*_*exo 9

erase从容器中删除指针,但不调用delete.

建议:

要么:

  • 使用shared_ptr/ unique_ptr(例如 boost::shared_ptr或std::shared_ptr取决于可用性):

    std::map<sf::String,std::shared_ptr<VisibleGameObject> >
    
    Run Code Online (Sandbox Code Playgroud)

    这将调用析构函数