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?

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.

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.

Detecting Expired Weak Pointers
How can I check if a weak pointer has expired before using it?
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