I am trying to learn a bit about std::weak_ptr
(semantics and usecases), however I cannot find many resources online. Cppreference didn't help at much, and there are a few other sites, but they didn't really help either.
Thank you in advance!
I am trying to learn a bit about std::weak_ptr
(semantics and usecases), however I cannot find many resources online. Cppreference didn't help at much, and there are a few other sites, but they didn't really help either.
Thank you in advance!
It is a non-owning reference to a shared_ptr
that can be safely upgraded to the shared_ptr
. weak_ptr
isn't frequently used. Never had to use it thus far. Though, it is partially because I usually shy away from shared_ptr
unless needed.
weak_ptr
can be used to manage lifetime of a shared_ptr
- which can be very messy. For instance, if a bunch of class instances have a copy of the shared_ptr
how do you delete it when you need to? Go over every single instance that leaked it who-knows-where?
Now instead you can hold a single shared_ptr
and supply only weak_ptr
and require that they upgrade to shared_ptr
only during active use. Once you need it deleted just clear the shared_ptr
and it will delete itself after its active duty is over.