Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In well designed code should you expect locking of weak_ptr to always succeed?

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.

like image 641
Ekalavya Avatar asked Feb 20 '23 04:02

Ekalavya


1 Answers

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.

like image 52
Matthieu M. Avatar answered Apr 09 '23 00:04

Matthieu M.