Course Content
C++ Smart Pointers
C++ Smart Pointers
Important Weak Pointer Functions
The expired() Function
Before calling lock()
, you can check whether a weak pointer is still valid using the expired()
method. This function returns true
if the object has been destroyed and false
otherwise.
expired_function
// Call `expired()` before `lock()` if (!p_weak.expired()) { // Lock only if the object is still alive auto p_shared = p_weak.lock(); p_shared->update(); } else { std::cout << "Object no longer exists" << std::endl; }
Calling expired()
before locking the weak pointer helps determine whether the referenced object still exists.
The use_count() Function
Although a weak pointer does not affect an object's reference count, it can be useful to know how many std::shared_ptr
instances are managing the same object. The use_count()
function returns this number.
use_count_function
std::shared_ptr<int> p_shared = std::make_shared<int>(42); std::weak_ptr<int> p_weak(sharedPtr); // Should output one std::cout << p_weak.use_count() << std::endl;
The reset() Function
To release a weak pointer from observing an object, use the reset()
function. This makes the weak pointer empty, meaning it no longer points to any object.
reset_function
std::weak_ptr<int> p_weak(sharedPtr); // After this, `p_weak` no longer observes the `p_shared` object p_weak.reset();
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.
swap_function
std::shared_ptr<int> p_shared_A = std::make_shared<int>(10); std::shared_ptr<int> p_shared_B = std::make_shared<int>(20); std::weak_ptr<int> p_weak_A(p_shared_A); std::weak_ptr<int> p_weak_B(p_shared_B); // Swaps the objects `p_weak_A` and `p_weak_B` p_weak_A.swap(weakPtrB);
initially p_weak_A
initially observes the object managed by p_shared_A
, while p_weak_B
observes the object managed by p_shared_B
.
After calling swap()
, p_weak_A
begins observing the object managed by p_shared_B
, and p_weak_B
observes the object managed by p_shared_A
.
Thanks for your feedback!