开发者

Auto detaching objects?

I have a mother class that stores the pointers to some objects in a list. I want these objects开发者_Python百科 to detach themselves from the list when they are destroyed. Can anyone suggest some good ways to do this please?


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜