Weak Pointers with std::weak_ptr

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?

Illustration representing computer hardware

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.

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:

  • 124 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