What's a little bit tricky about C++'s memory handling is to find a consistent definition of who's responsible for the creation and deletion of an object.
This might be a bit far out for the beginning, but most of that hassle is eliminated when one just specifies an object's "owner" and delete the object along with its' owner.
This can be achieve by a simple base-class:
class BaseObject
{
public:
// constructor
BaseObject(BaseObject *parent= NULL)
: mParent(parent)
{
// if a parent is specified, notify the parent about its' new child.
if (mParent)
mParent->addChild(this);
}
// destructor
~BaseObject()
{
// remove the child from the parent
if (mParent)
mParent->deleteChild(this);
// delete all children
while (!mChildList.empty())
delete mChildList.pop_front();
}
void addChild(BaseObject *child)
{
// add new child to child-list
mChildList.insert(child);
}
void deleteChild(BaseObject *child)
{
// erase child from child-list
mChildList.erase(child);
}
private:
BaseObject *mParent; // pointer to the parent-object
Set<BaseObject*> mChildList; // list of child-objects (most standard-containers do as well)
}
Now all you do is derive from "BaseObject" and use it like this:
void MyClass::doWickedThings()
{
Object *obj1= new Object(this);
Object *obj2= new Object(this);
Object *obj3= new Object(this);
// ...
}
Now when deleting MyClass, all objects allocating along with it get deleted automatically.
- then the instance no longer has a pointer and therefore can't be freed.
- but we reassigned the only pointer, so that instance can't be freed
A solution for this would be overloading the "=" operator, so that an already existing object gets deleted first or, more generally, handle a
reference counter to test if any other instances are still refering to the object (realizing most of a garbage-collector).
You can have a look at
boost for such mechanisms.
The best way to go, though, still is handling your heap correctly in first place
