std::unique_ptr memory leak?

Hello guys,

I have this issue with this gamestate system I'm trying to implement this is the pseudo code:

1
2
3
4
5
6
while(gameRunning)
(
HandleEvents();
Update();
Render();
)


Nothing new there, but then in my update function I have each state call it's update method, I am using a std::stack based gamestate system, and I am using std::unique_ptr.

The pseudo code would be like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Update()
{

if(!states.empty())
{

std::unique_ptr<GameState> nextState = states.top()->NextState();
if(nextState != nullptr)
{

if(nextState->popLastState() && states.size() > 1)
{
      states.pop();
}

states.push(std::move(nextState));

}

}

states.top()->Update();
}


then when I want to change states I just change the variable member m_State of the std::unique_ptr<GameState> object which is returned by states.top()->NextState(); to the state I want like <MenuState>

 
m_State = createState<MenuState>();


It works fine but then it invokes the state's constructor as it is effectively creating a new ptr each time...

so it is creating new objects that I create in the constructor EACH time I switch states, is leaking memory like crazy and that is not what I want...

When I switch to shared_ptr this does not happen, can somebody tell me why that is, or a fix to this maybe...
After revisingt all of my GameState derived classes and GameState class it self, the problem was I did not declare the base abstract class GameState destructor as virtual..... and I apologize for thread, which was pretty much useless, I should have debugged my project better...
> m_State = createState<MenuState>();
> so it is creating new objects that I create in the constructor EACH time I switch states

If the number of different MenuStates are not very large, consider pre-creating a GameState derived class object for each state and then switching to one of these when a state transition takes place.
Last edited on
Yeah that is what I am going to do but it doesn't matter because when the function goes out of scope and gets popped off it deletes itself, the problem really was the virtual destructor.

I hate when little things like this affect the program in such an enormous way, thanks for your suggestion.
> I hate when little things like this affect the program in such an enormous way

Just get into the habit of declaring a virtual destructor for any class that is designed for inheritance. Not having a virtual destructor should be the exception rather than the rule.
Topic archived. No new replies allowed.