-3
這麼長的故事,我正在爲我的遊戲編寫代碼,並無法讓它工作。我正在初始化一些指針,然後決定不刪除我分配的指針,然後神奇地開始工作。到底是怎麼回事?我非常困惑。不刪除指針?什麼?這是如何工作的
我之所以決定擺脫指針是因爲我在這個鏈接找到的代碼。
Game State Machine - GameDevGeek
GameStatesMachine.h
#ifndef __GAMESTATESMACHINE_H__
#define __GAMESTATESMACHINE_H__
#include <vector>
#include <stdio.h>
#include "GameStates.h"
class GameStatesMachine
{
private:
std::vector<GameStates *> data;
GameStatesMachine() {};
GameStatesMachine(GameStatesMachine const&);
void operator=(GameStatesMachine const&);
// you do not delete it this is for cleaning purposes
~GameStatesMachine()
{
while (!data.empty())
pop_back();
printf("GameEngine cleanup\n");
}
public:
static GameStatesMachine& Instance()
{
static GameStatesMachine g_instance;
return g_instance;
}
void push_back(GameStates * state);
void pop_back();
void changeState(GameStates * state);
void render();
void process();
void update();
};
#endif
GameStatesMachine.cpp
#include "GameStatesMachine.h"
void GameStatesMachine::push_back(GameStates * state)
{
if (!data.empty())
data.back()->pause();
data.push_back(state);
data.back()->onEnter();
}
void GameStatesMachine::pop_back()
{
if (!data.empty()) {
data.back()->onExit();
data.pop_back();
}
if (!data.empty())
data.back()->resume();
}
void GameStatesMachine::changeState(GameStates * state)
{
if (!data.empty())
pop_back();
push_back(state);
}
void GameStatesMachine::render()
{
data.back()->render();
}
void GameStatesMachine::process()
{
data.back()->process();
}
void GameStatesMachine::update()
{
data.back()->update();
}
你刪除了什麼指針,你在哪裏刪除它? – Thebluefish
提供一個SSCCE –
我_was_刪除它在pop_back()後data.back() - > onExit();和之前data.pop_back(); 指針只是一個叫做狀態的對象。 該代碼無法正常工作,因此在網上查找其他人做了什麼並注意到有人沒有刪除它的例子,我決定複製他,然後我的代碼神奇地工作。不應該刪除它創建一個內存泄漏?或者矢量pop_back只是爲我調用解構器? – KojinKuro