I have a mother class that stores the pointers to some objects in a list. I want these objects to detach themselves from the list when they are destroyed.
Can anyone suggest some good ways to do this please?
I have a mother class that stores the pointers to some objects in a
Share
The crude way is to store the container reference (or pointer) in the objects in the list and remove themselves in their destructors:
Note that this makes the
Containedclass non-copyable.The easy way is to use some framework that already provides such functionality. Eg. if you use Qt, you would just derive the
Containedclass fromQObjectand storeQPointer<Contained>in the Container. TheQPointerwould be set to zero once the contained object is deleted.Or, if you use some memory management facilities like
boost::shared_pointer, (I assume the Container doesn’t own theContainedobjects, otherwise, it knows best when the child object dies), you would use a weak pointer in theContainer, which has similar functionality.