std::weak_ptr::lock

1
std::shared_ptr<T> lock() const;
(since C++11)

Creates a new std::shared_ptr that shares ownership of the managed object. If there is no managed object, i.e. *this is empty, then the returned shared_ptr also is empty.

Effectively returns expired() ? shared_ptr<T>() : shared_ptr<T>(*this), executed atomically.

Parameters

(none).

Return value

A shared_ptr which shares ownership of the owned object.

Exceptions

noexcept specification:
noexcept

Notes

Both this function and the constructor of std::shared_ptr may be used to acquire temporary ownership of the managed object referred to by a std::weak_ptr. The difference is that the constructor of std::shared_ptr throws an exception when its std::weak_ptr argument is empty, while std::weak_ptr<T>::lock() constructs an empty std::shared_ptr<T>.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <memory>
  
void observe(std::weak_ptr<int> weak)
{
    if (auto observe = weak.lock()) {
        std::cout << "\tobserve() able to lock weak_ptr<>, value=" << *observe << "\n";
    } else {
        std::cout << "\tobserve() unable to lock weak_ptr<>\n";
    }
}
  
int main()
{
    std::weak_ptr<int> weak;
    std::cout << "weak_ptr<> not yet initialized\n";
    observe(weak);
  
    {
        auto shared = std::make_shared<int>(42);
        weak = shared;
        std::cout << "weak_ptr<> initialized with shared_ptr.\n";
        observe(weak);
    }
  
    std::cout << "shared_ptr<> has been destructed due to scope exit.\n";
    observe(weak);
}

Output:

1
2
3
4
5
6
weak_ptr<> not yet initialized
        observe() unable to lock weak_ptr<>
weak_ptr<> initialized with shared_ptr.
        observe() able to lock weak_ptr<>, value=42
shared_ptr<> has been destructed due to scope exit.
        observe() unable to lock weak_ptr<>

See also

checks whether the referenced object was already deleted
(public member function)
doc_CPP
2025-01-10 15:47:30
Comments
Leave a Comment

Please login to continue.