Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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).

like image 623
Anne Quinn Avatar asked Jan 19 '26 12:01

Anne Quinn


1 Answers

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.

like image 93
Brian Bi Avatar answered Jan 21 '26 05:01

Brian Bi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!