c++shared-ptrweak-ptr

Casting shared_ptr<Type> to weak_ptr<void> and back


How would I get a weak_ptr<void> to a shared_ptr<Type>?

How would I lock a weak_ptr<void> and ultimately produce a shared_ptr<Type>?

Type has a non-trivial destructor, is it right to assume weak_ptr<...> will never call this destructor?

The void weak pointer is what I want in this case, it's used only to keep tabs on the reference count of shared pointers of multiple types, and give out shared pointers to existing objects without itself owning the object (it's part of a one object many references resource manager).


Solution

  • How would I get a weak_ptr<void> to a shared_ptr<Type>?

    std::shared_ptr<Type> is implicitly convertible to std::weak_ptr<void>.

    How would I lock a weak_ptr<void> and ultimately produce a shared_ptr<Type>?

    Call lock() to get std::shared_ptr<void>, then use std::static_pointer_cast.

    Type has a non-trivial destructor, is it right to assume weak_ptr<...> will never call this destructor

    Yes. Whenever the last shared_ptr is destroyed, the object is destroyed. If you want to keep the object alive, you should be storing shared_ptr<void> and not weak_ptr<void>. If you don't want to keep the object alive but you just want the weak_ptr to always know the reference count, then there is no problem.