When working with weak pointers, it's important to check if the pointed-to object still exists before attempting to access it. You can do this using either the expired()
method or by attempting to lock()
the weak pointer:
Using expired()
:
#include <memory>
#include <iostream>
int main() {
auto SharedPtr{std::make_shared<int>(42)};
std::weak_ptr<int> WeakPtr{SharedPtr};
if (WeakPtr.expired()) {
std::cout << "WeakPtr has expired";
} else {
std::cout << "WeakPtr is valid. Value: "
<< *WeakPtr.lock();
}
}
WeakPtr is valid. Value: 42
Using lock()
:
#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 << "WeakPtr is valid. Value: "
<< *LockedPtr;
} else {
std::cout << "WeakPtr has expired";
}
}
WeakPtr is valid. Value: 42
Both approaches allow you to safely handle cases where the weak pointer may have expired. Use expired()
if you just need to check the status, and use lock()
if you also need to access the pointed-to object if it exists.
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