We use composition, when an object has a single parent, which should care for the object's lifetime. We use unique_ptr
when in the same situation, but the object can be nullptr
.
We use shared_ptr
when several external entities may need our object, so its lifetime is extended until the last of those external entities loses interest.
Here I want to ask about another lifetime situation. What if the object needs to live the shortest of several durations?
Here is an example. Let's have a one-shot timer, which stores a functor and executes it after a the counting is complete. It makes sense to me*, that this timer object is destroyed after:
1. fulfilling its task - therefore it should be able to destroy istelf
or
2. the parent loosing interest in the timer - so the parent should be able to
destroy the object as well
Currently, I using an awkward implementation with unique pointers. What would be a good pattern / guideline / implementation of this problem?
* reasons: 1) the functor could be owning some other resources 2) the timer could have been set to a very large number, and then abandoned 3) if the parent has been destroyed, we generally don't want to invoke its callbacks
Aucun commentaire:
Enregistrer un commentaire