Detecting Expired Weak Pointers

How can I check if a weak pointer has expired before using it?

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.

Weak Pointers with 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

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Creating a Shared Pointer from a Weak Pointer
How do I create a shared pointer from a weak pointer to access the pointed-to object?
Performance Impact of Weak Pointers
Do weak pointers have any performance overhead compared to raw pointers?
Using Weak Pointers in Multithreaded Environments
Are weak pointers thread-safe? How can I use them safely in multithreaded code?
Storing Weak Pointers in Containers
Can I store weak pointers in containers like std::vector or std::map?
Using Custom Deleters with Weak Pointers
Can I use custom deleters with weak pointers like I can with unique_ptr and shared_ptr?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant