gartenriese
gartenriese

Reputation: 4356

Add and remove itself from container

I have a class Drawable and a class DrawableManager. The DrawableManager should have a container of pointers to Drawables, where it can look up the properties of the Drawable objects and draw them appropriately.

Now I want that a Drawable object will add itself to the DrawableManager on creation and remove itself on deleting. Is something like that possible? If it is, is it okay to do it or is there a better way?

The way I have it now is that I have shared_ptrs to the Drawable objects and DrawableManager has a vector of weak_ptrs to those objects, and I manually add the objects to the manager. I want this process automated though.

Upvotes: 0

Views: 221

Answers (1)

Sneftel
Sneftel

Reputation: 41474

Well, you can pass a DrawableManager* to the Drawable constructor, which adds itself and then removes itself in the destructor. Note that at these times, its dynamic type will be Drawable instead of whatever the derived type is, so be careful not to call virtual methods as an immediate result of the addition.

However, I suggest that you not do this. It's often useful to separate existence from membership, to have a Drawable which is not part of a "DrawableManger" (and incidentally, see http://blog.codinghorror.com/i-shall-call-it-somethingmanager/ about that). "Automating" the process removes that flexibility, for essentially no usability win.

Upvotes: 1

Related Questions