Sign in to follow this  
Plethora

Logic error of sorts involving a stack of unique_ptrs

Recommended Posts

So I'm guessing I'm just not getting something about how exactly unique_ptr works in this context but I haven't been able to find any info on the web for why my program is behaving this way.  I have an std::stack object that contains unique_ptrs to Controller objects.  My controller objects are basically event handlers for the different "screens" in my game, ie the world map screen, the battle screen, the town screen, etc.  When the player enters a given screen from elsewhere, I push a new instance onto the stack, and when a screen is finished I pop it off.  So, for example, if a player enters a town, I push the town controller (which is derived from a plain controller), when the player leaves town the town controller is popped off and the world map regains control.  I do this more or less as follows:

//declare the stack at the beginning of the program
std::stack<std::unique_ptr<Controller>> screenStack;

//start the game (in this case with the world map)
screenStack.emplace(new World_Map_Controller());

//battle begins...
screenStack.emplace(new Battle_Controller(&playerOne));

//and this code is run at every iteration:
if(screenStack.top()->isFinished())
{
     screenStack.pop();
}

 

Now, this all works completely fine at first glance.  However, by design a new instance is supposed to be created when the player enters a new battle (for example), and this is not happening.  Like, a player enters a battle, the battle ends (and thus is popped off the stack) and the player returns to the world map.  The player then enters a new battle, which should be created fresh.  In my current implementation, if I enter a battle, do some stuff, then exit it (either naturally or artificially), and then enter a new battle, it picks up where the old battle left off, it is NOT creating a new instance like it should be.

 

I don't understand how this is happening, as it is my understanding that, once the battle gets popped off the stack, it should be getting destroyed.  However the destructor isn't even getting called (I've checked).

 

So what am I missing?

 

EDIT:  Half solved the problem... the battle controller was using some data that was in fact persistent (thought it shouldn't have been, now corrected).  I'm still curious as to why the destructor was never getting called though...

Edited by Plethora

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this