C ++状态更改不删除旧状态?

时间:2016-03-30 23:30:57

标签: c++ class destructor

我正在使用Visual Studio和SDL来创建一个简单的RPG游戏,但是当我改变游戏状态时,我注意到(当添加音乐时)音乐一直在播放,即使我将它停留在析构函数中。如果我在改变状态之前就停止音乐,音乐会停止(这让我意识到每次我改变游戏状态时,旧的状态仍然存在,我认为这会占用大量的内存(如果我制作游戏)很大,并改变了很多状态。)

我的州级课程设置如下:

// Gamestate.h
#pragma once
// includes here

class GameState
{
public:
  virtual ~GameState() {}
  virtual void Update() {}
  virtual void HandleEvents() {}
  virtual void Logic() {}
  virtual void Draw(Graphics& gfx) {} // Graphics is my own class

  GameState* getCurrentState()
  {
    return currentState;
  }

protected:
  SDL_Renderer* renderer;
  GameState* currentState;
  Timer timer; // my own timer class
};

// GameStates.h; different than GameState.h
#pragma once
// includes here

class IntroGameState : public GameState
{
public:
  IntroGameState(SDL_Renderer* renderer, KeyboardClient& kbd);
  ~IntroGameState();
  void HandleEvents();
  void Logic();
  void Draw(Graphics& gfx);

private:
  Mix_Music* theme;
  // other variables defined here
};

// GameStates.cpp
IntroGameState::IntoroGameState(SDL_Renderer* renderer, KeyboardClient& kbd)
{
  GameState::renderer = renderer;
  currentState = this;
  timer.Start();

  theme = Mix_LoadMUS("theme.wav");
  Mis_PlayMusic(theme, 0);
}
IntroGameState::~IntroGameState()
{
  // This line does nothing (destructor not being called?)
  Mix_HaltMusic();

  delete theme;
  theme = NULL;
};
void IntroGameState::Logic()
{
  if (timer.ElapsedTime() >= 5) // if 5 seconds pass
  {
    // This line works
    Mix_HaltMusic();
    // I tried:
    // delete this;
    // delete currentState;
    // currentState = NULL; realized this was pointless when I just initialize it next

    currentState = new MovieSceneState(renderer, kbd);
}

// Game.cpp (where i actually change the state
Game::Game()
{
  // currentState here is defined within game.h
  currentState = new IntroGameState(renderer, kbd);
}
void Game::ComposeFrame()
{
  currentState->HandleEvents();
  ChangeState();
  currentState->Logic();
  currentState->Draw(gfx);
}
void ChangeState()
{
  GameState* s = currentState->GetCurrentState();
  currentState = s;
}

0 个答案:

没有答案