tags:

views:

35

answers:

2

Hi,

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?

A: 

you can add reference/pointer to the mother class in those classes and when destructor is called they call mother.Detach(this)

Andrey
+1  A: 

The crude way is to store the container reference (or pointer) in the objects in the list and remove themselves in their destructors:

class Contained;
class Container {
  std::list<Contained*> children;
public:
  ...
  void goodbye(Contained*);
};
class Contained {
  Container& c; // you set this in the constructor
public:
  ~Contained() { c.goodbye(this); }
};

Note that this makes the Contained class 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 Contained class from QObject and store QPointer<Contained> in the Container. The QPointer would 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 the Contained objects, otherwise, it knows best when the child object dies), you would use a weak pointer in the Container, which has similar functionality.

jpalecek
Thank you.Yes I have thought of this way, but the thing is: there's no guarantee that the mother object will exist till the child object is destroyed. (I guess calling it "mother" was a little misleading XD ). If mother is destroyed before child, bad things will happen when the destructor of child is called...
The weak pointer way may work for me. Let me look into it. Thank you.
The problem with the last suggestion is that the weak pointer won't be automatically removed from the list when the object dies. You'll need to do a bit more work to avoid an ever-growing list of dead pointers.
Mike Seymour
@twf666: the problem of the children outliving the mother can be solved by giving the children weak pointers rather than references, or plain pointers that the mother nullifies in her destructor.
Mike Seymour
Ok I'm definitely trying the weak pointer way. Thanks. :)Just out of curiosity, how can weak pointers be so smart to know when the objects they point to are destroyed?
@twf666: all the shared and weak pointers to an object also have a (private) pointer to a shared control structure, containing the count of shared pointers and a collection of pointers to all the weak pointers. When the last shared pointer is destroyed, it uses that to find and invalidate the weak pointers. At least that's one way of doing it; there are other variations.
Mike Seymour