When you wish to make an access using a weak pointer, you are first advised to get a strong pointer to the pointed object by locking. Locking may not succeed in case the pointed object was deleted earlier.
It seems to me that unless you did something wrong in breaking the cycles to decide what is a weak pointer, locking will succeed. So you are locking just to cross-check your design.
Is this correct?
I have seen some remarks about caching, but they seem like an abuse of weak_ptrs. But of course one man's abuse is another man's innovation. I would like to hear opinions.
No, you should not.
Suppose you maintain a list of observers, upon destruction you would need to unsubscribe the observer from the object(s) it was observing, however that requires that the observer maintains a list of the entities it observes, leading to a cycle.
To simplify the design, it is simpler to introduce a level of indirection. A broker between the observer and the entity will allow the observer to be destroyed and the entity querying for its liveness.
How to ? Simply you can allocate a std::shared_ptr<Observer>
and have an entity only retain a std::weak_ptr<Observer>
, then when an entity iterate over its list of observers, it can cull the references to those who died since the last iteration.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With