GC can collect object allocated in function, despite a pointer to the object living on?

"岩倉 澪" via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Aug 16 15:36:50 PDT 2014


Hello, I've been interested in the D language for a few years
now, but only dabble. I have read TDPL and recently started
reading D Cookbook. On the side, I started to write a small game
in D, but ran into a problem. I would greatly appreciate any help!

My design is a simple state machine. I have a module game.states,
which includes:

interface IState{
     void handleEvents();
     void renderFrame();
}

IState *currentState;
string nextState;

void changeState(){
      if(nextState != "WaitState" && nextState != "ExitState"){
          auto newState = cast(IState)
Object.factory("game.states."~nextState);
          import std.exception;
          enforce(newState);
          currentState = &newState;
          nextState = "WaitState";
      }
}

class TitleState : IState{
      void handleEvents(){
      ...
      }

      void renderFrame(){
          ...
          }
      }
      ...
}

and the game loop is of the following form:

//init state
nextState = "TitleState";
changeState();

//game loop
while(nextState != "ExitState"){
      currentState.handleEvents();
      currentState.renderFrame();
      changeState();
}

However, it appears that the changeState function has a bug.
I believe the problem is that when changeState returns, newState
gets garbage collected, despite currentState pointing to it.
I come from a C++ background, so I am not used to garbage
collection.
Normally the changeState function would explicitly free the old
state, and allocate the new one.

Am I correct that newState is liable to be collected after
changeState returns?
Is there an easy fix?
Is my design fundamentally flawed within the context of garbage
collection?
If so, what kind of design would you recommend instead?


More information about the Digitalmars-d-learn mailing list