Contenido del Curso
C++ Smart Pointers
C++ Smart Pointers
Important Weak Pointer Functions
To leverage the full potential of weak pointers, it’s important to know about the following functions.
Before making a call to lock()
, you can check whether a weak pointer is still valid (i.e., whether the pointed object still exists) by using the expired()
method. This function returns true if the referenced object has been destroyed, and false otherwise.
In the above example, we call expired()
before locking the weak pointer and accessing the referenced object.
The use_count() function
While a weak pointer does not affect the reference count of an object, it's often useful to know how many shared pointers are managing the same object. The use_count()
function returns this number.
The reset() function
To release a weak pointer from its duties of observing an object, you can use the reset()
function. This will make the weak pointer empty, i.e. it no longer points to any object.
The swap() function
The swap()
function can be used to exchange the contents of two weak pointers. This is particularly useful when you want to change the objects that the two weak pointers are observing, without altering the ownership or lifetime of the dynamic objects.
In this snippet, weakPtrA
initially observes the object managed by sharedPtrA
, and weakPtrB
observes the object managed by sharedPtrB
.
After we call swap()
, weakPtrA
starts pointing to the object that was managed by sharedPtrB
and vice versa.
¡Gracias por tus comentarios!