Weak Pointer
Weak pointers in C++ are smart pointers that hold a non-owning ("weak") reference to an object that is managed by a shared pointer. They are used to break circular references between shared pointers and to observe an object without affecting its lifetime. Unlike shared pointers, weak pointers don't increment the reference count of the object they point to.
Here's a simple example to demonstrate the use of weak pointers:
Run it here.
Key points in this example:
We define a simple
Person
class with a constructor, destructor, and agreet()
method.In
main()
, we create ashared_ptr<Person>
namedshared
.We then create a
weak_ptr<Person>
namedweak
from theshared
pointer.To use the weak pointer, we need to call its
lock()
method, which returns ashared_ptr
. If the object still exists, we can use it; otherwise,lock()
returns a null pointer.After resetting the
shared
pointer, thePerson
object is destroyed because there are no moreshared_ptr
s pointing to it.When we try to use the weak pointer again,
lock()
returns a null pointer, showing that the object no longer exists.
Last updated