Why's my vector element all garbage?

2019-09-16 15:17发布

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! :)

0条回答
登录 后发表回答