Why's my vector element all garbage?

家住魔仙堡 提交于 2019-12-11 16:01:43

问题


I have a GameLobby class that keeps a list of the currently active games. I want to fetch the active games from a GameLobby (singleton) object, and display these to the user.

(Disclaimer: I'm pretty new to C++, so the following code isn't exactly stellar. Neither is it the complete code, but I feel confident that all the relevant instructions have been included.)

First some definitions

class GamesMenu : public MyGameLayer
{
private:
    std::vector<Game*>* _activeGames;
    void displayGamesList();
    void refreshGamesList();
};

and

class MyGameLayer : public cocos2d::CCLayer
{
private:
    GameLobby* _gameLobby;
public:
    GameLobby* getGameLobby();
};

and

GameLobby* MyGameLayer::getGameLobby()
{
    return _gameLobby;
}

Now to the problem at hand. I want to execute GamesMenu::refreshGamesList() which looks like this:

void GamesMenu::refreshGamesList()
{
    GameLobby* gameLobby = getGameLobby();
    if (gameLobby) {
        _activeGames = gameLobby->getActiveGames();
        Game* game = _activeGames->at(0); // For debug purposes only - this game is NOT garbage
    }
    displayGamesList();
}

where

std::vector<Game*>* GameLobby::getActiveGames()
{
    if (_loggedInPlayer) {
        refreshActiveGames(_loggedInPlayer->GetPlayerToken());
    } else {
        refreshActiveGames("");
    }
    return &_activeGames;
};

and std::vector<Game*> _activeGames is a private member of GameLobby.

However, when execution hits displayGamesList(), things get pretty bad

void GamesMenu::displayGamesList()
{
    for (unsigned i = 0; i < _activeGames->size(); i++) {
        Game* game = _activeGames->at(i); // The contents of game is garbage. Why?
        std::string opponentName = game->GetOpponentName(); // This I don't even want to talk about 
    };
    /* Supressed drawing stuff */
}

When I inspect game in GamesMenu::refreshGamesList, the contents of game seems fine. When I inspect game in GamesMenu::displayGamesList, the contents is all garbage. It is as if the elements of the vector points to the wrong data or something.

Can anyone please help me untangle myself out of this mess? Thanks! :)

来源:https://stackoverflow.com/questions/18297093/whys-my-vector-element-all-garbage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!