game-programming-patterns icon indicating copy to clipboard operation
game-programming-patterns copied to clipboard

Command unit_ pointer invalidation?

Open 1f604 opened this issue 6 years ago • 0 comments

Hi @munificent Regarding the following code snippet from chapter 2:

class MoveUnitCommand : public Command
{
public:
  MoveUnitCommand(Unit* unit, int x, int y)
  : unit_(unit),
    xBefore_(0),
    yBefore_(0),
    x_(x),
    y_(y)
  {}

  virtual void execute()
  {
    // Remember the unit's position before the move
    // so we can restore it.
    xBefore_ = unit_->x();
    yBefore_ = unit_->y();

    unit_->moveTo(x_, y_);
  }

  virtual void undo()
  {
    unit_->moveTo(xBefore_, yBefore_);
  }

private:
  Unit* unit_;
  int xBefore_, yBefore_;
  int x_, y_;
};

If the unit is later destroyed via let's say a KillUnitCommand, the natural thing to do would be to call delete on the Unit object, which would mean that the unit_ pointer is no longer valid. I can't think of a way that an undo for the KillUnitCommand would restore pointer validity for all the previous commands in the command history.

Is this a legitimate concern?

1f604 avatar Dec 29 '18 17:12 1f604