简体   繁体   中英

Using smart pointers for observation purposes

i have a large application where task part is modeling objects and the other part is timeline-backed animation of objects. It may be possible that a user deletes an animateable object while the timeline is still animating it.

The timeline accesses (animates) the objects through smart pointers, so it would be perfectly easy to check the object for existence by checking the smart pointer for validity before using it. But this feels a little bit 'dirty' ... like using a safety belt for fixing luggage. But whatever other mechanism we discussed was more or less the same: an object being registered somewhere else and de-registering itself on deletion, exactly what a smart pointer does anyways.

Is this a valid use case for testing smart pointer validity?

In my opinion std::weak_ptr will be good for this job. Weak pointer does not guaratee existence of object under the pointer, if object will be deleted it will be known to other objects referencing for animateable object. Always to use this pointer it has to be locked ( enforcing checking its existence ).

I don't see how you can use std::shared_ptr , here, because it's an Observer Effect problem (by testing something, you're altering it). If you hold an std::shared_ptr to an object, it will be valid by definition.

OTOH, there is std::weak_ptr , which is built exactly for this purpose. It acts as an observer for the shared_ptr only.

std::weak_ptr is a smart pointer that holds a non-owning ("weak") reference to an object that is managed by std::shared_ptr. It must be converted to std::shared_ptr in order to access the referenced object.


If your program is multithreaded, incidentally, you need to handle the case of someone deleting the object while you're observing it, through some other mechanism (eg, locking).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM