tags:

views:

76

answers:

1

Recently I implemented a 'Paused' screen in my game. Since I wanted it to be a separate game state, I needed to somehow save the data from when the player paused the game to when they re-enter. However, when states are switched the pointer to the previous state is deleted.

Thus, I decided for the Paused constructor to take a copy of the Level ( a class ), so that it could hold it until the user decided to resume. Then it would set the next state using that Level that was copied.

The code to set the next state to paused looks like this...

p_Game->SetNextState( new Paused( *this ));

Unfortunately, when I enter the command to pause, the program crashes. I debugged it until I found that the problem seems to have something to do with a pointer to the boss that the Level class holds as a member variable. The way the game loop operates, it first handles events, then runs logic, then renders, and if a state has been set, it updates to the new one.

The program crashes whenever an operation is done on the Boss pointer, which occurs during the run logic and rendering portion of Level, but before the game state is switched to paused. Note, this Boss pointer is allocated upon Level construction, and deallocated upon destruction. Could passing a copy of the current Level somehow mess with a pointer being held in a member variable?

+7  A: 

Did you define an actual copy constructor that deep-copies the Level object, creating a new Boss object, et cetera?

Or did you just use the one automatically provided by the compiler, which is a shallow copy?

If the latter, that's where you're running into issues: because it's a shallow copy, the pointer for the Boss object in the new level is pointing to the same Boss object as in the level you're copying... but that Boss object is getting deallocated when your original level object (not the copy, but the one you made a copy of) destructs.

Even if you wrote your own constructor, you may still need to make sure that you're doing a deep copy instead of a shallow copy.

More on copy constructors: link

Amber
Thanks. Informative and correct post.
Anonymous