Reputation: 195
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?
Upvotes: 0
Views: 230
Reputation: 76336
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 (e.g., locking).
Upvotes: 1
Reputation: 1427
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 ).
Upvotes: 1