game-programming-patterns
game-programming-patterns copied to clipboard
Command unit_ pointer invalidation?
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?