I have a "parent" object that manages the lifetime of several "child" objects. The objects do some stuff and after they are done, they signal to its parent (via a callback) that they are done and can be destroyed.
A toy example:
#include <list>
class Child;
class IChildListener
{
public:
virtual void on_done(Child *child) = 0;
};
class Child
{
public:
Child(IChildListener *parent)
: m_parent(parent)
{
}
void do_stuff()
{
m_parent->on_done(this);
}
protected:
IChildListener *m_parent;
};
class Parent : public IChildListener
{
public:
void on_done(Child* child) {
m_children.remove(child);
delete child;
}
Child *create_child() {
Child* child = new Child(this);
m_children.push_back(child);
return child;
}
protected:
std::list<Child*> m_children;
};
int main(int argc, char** argv) {
Parent p;
Child *c = p.create_child();
c->do_stuff();
}
The problem is that, effectively a child is destroyed during a call of its own method and that's certainly not a good idea. Is there a pattern for doing such things?