Contenido del Curso
C++ Smart Pointers
C++ Smart Pointers
Understanding Weak Pointers
Weak pointers are a type of smart pointer added to C++ to address issues, like circular references, that can arise when working with shared pointers. Just like unique and shared pointers, they are a part of the <memory>
header file and are defined in the std
namespace.
Note
Smart pointer
std::weak_ptr
doesn’t own the object it points to. This essentially means that a weak pointer doesn’t increase the reference count of the object.
The main purpose of weak pointers is to provide a way to access an object that might be owned by multiple shared pointers, without extending the lifetime of that object.
Example
Imagine we have an object that four shared pointers are pointing to. If we then add a weak pointer that points to the same object, it won't affect the object's existence. This is because weak pointers don't have a say in whether the object stays around or not. So, when all the shared pointers go out of scope or are reset, the object will be deleted, even though the weak pointer is still there.
This behavior of weak pointers can be particularly useful when you want to monitor a dynamic shared object, but don’t want to artificially elongate its existence. For instance, suppose there is a shared resource counter that you want to access from an observer class. By using a weak pointer, the observer can access the counter to read its value without influencing when the counter gets deallocated. The counter lives and dies according to the rules of its shared pointers, not the weak ones observing it.
The lifecycle of a weak pointer
Weak pointers are observers. They can observe and access the object, but their observation doesn't affect the object's lifetime.
The lifecycle of a weak pointer is tied to the lifecycle of the object, which is managed by shared pointers. When the last shared pointer to the associated object is destroyed, the object is deallocated. The weak pointer doesn’t prevent this deallocation. Post-destruction, the weak pointer enters a state of emptiness; it still exists but is now considered expired.
Real world analogy
Think of a weak pointer like a ticket to an event. While the event is on (the object is alive), you can use the ticket to enter (access the object). However, the ticket itself doesn't keep the event going (doesn't extend the object's lifetime). If the event ends (the object is destroyed), your ticket becomes worthless (the weak pointer becomes invalid).
¡Gracias por tus comentarios!