Weak Pointers with std::weak_ptr

Detecting Expired Weak Pointers

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

Illustration representing computer hardware

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.

This Question is from the Lesson:

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

Answers to questions are automatically generated and may not have been reviewed.

This Question is from the Lesson:

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

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 125 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved