To access the object pointed to by a weak pointer, you need to create a shared pointer from it using the lock()
method. This will return a shared_ptr
that shares ownership of the object, if it still exists.
#include <memory>
#include <iostream>
int main() {
auto SharedPtr{std::make_shared<int>(42)};
std::weak_ptr<int> WeakPtr{SharedPtr};
if (auto LockedPtr{WeakPtr.lock()}) {
std::cout << "Accessed value: " << *LockedPtr;
} else {
std::cout << "The object no longer exists";
}
SharedPtr.reset();
if (auto LockedPtr{WeakPtr.lock()}) {
std::cout << "\nAccessed value: "
<< *LockedPtr;
} else {
std::cout << "\nThe object no longer exists";
}
}
Accessed value: 42
The object no longer exists
It's crucial to check the returned shared_ptr
before attempting to dereference it, as the original object may have been destroyed. If lock()
returns an empty shared_ptr
, dereferencing it will lead to undefined behavior.
By using lock()
, you ensure that the object will remain alive at least as long as the shared_ptr
created from the weak_ptr
exists, preventing dangling pointers.
Answers to questions are automatically generated and may not have been reviewed.
std::weak_ptr
A full guide to weak pointers, using std::weak_ptr
. Learn what they’re for, and how we can use them with practical examples