Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Important Weak Pointer Functions | Weak Pointers
C++ Smart Pointers
course content

Contenido del Curso

C++ Smart Pointers

C++ Smart Pointers

1. Introduction to Smart Pointers
2. Unique Pointers
3. Shared Pointers
4. Weak Pointers
5. References
6. Advanced topics

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

Which function should you use if you want to see if a pointed resource of a weak pointer still exists or not?

Which function should you use if you want to see if a pointed resource of a weak pointer still exists or not?

Selecciona la respuesta correcta

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 4. Capítulo 4
We're sorry to hear that something went wrong. What happened?
some-alt