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

Course Content

C++ Smart Pointers

C++ Smart Pointers

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

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

h

expired_function

copy
1234567891011
// 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.

h

use_count_function

copy
12345
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.

h

reset_function

copy
1234
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.

h

swap_function

copy
12345678
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.

question mark

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

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 4. Chapter 4
We're sorry to hear that something went wrong. What happened?
some-alt