J
Jonathan Ames
Moving to C++ from Java, I'm still confused by some aspects of memory
cleanup operations.
For example, let's say I have a class MovingObject which maintains a
pointer to another class MovementAlgorithm.
MovingObject has a method
SetMovementAlgorithm(MovementAlgorithm* movementAlgorithm)
if the body of this method reads
{
this->movementAlgorithm = movementAlgorithm;
}
is this a memory leak every time a new MovementAlgorithm is set (other
than the first time)? Because the previous movement algorithm isn't
deleted?
What is the correct way to handle this problem?
If I change the body of the method to read as follows :
if (this->movementAlgorithm != NULL) {
delete this->movementAlgorithm;
}
this->movementAlgorithm = movementAlgorithm;
I get program crash. All of the constructors for MovingObject
initialize the pointer variable either to NULL or through the new
operator. Can anyone explain this?
cleanup operations.
For example, let's say I have a class MovingObject which maintains a
pointer to another class MovementAlgorithm.
MovingObject has a method
SetMovementAlgorithm(MovementAlgorithm* movementAlgorithm)
if the body of this method reads
{
this->movementAlgorithm = movementAlgorithm;
}
is this a memory leak every time a new MovementAlgorithm is set (other
than the first time)? Because the previous movement algorithm isn't
deleted?
What is the correct way to handle this problem?
If I change the body of the method to read as follows :
if (this->movementAlgorithm != NULL) {
delete this->movementAlgorithm;
}
this->movementAlgorithm = movementAlgorithm;
I get program crash. All of the constructors for MovingObject
initialize the pointer variable either to NULL or through the new
operator. Can anyone explain this?