Reference

public member function
<memory>

std::weak_ptr::lock

shared_ptr<element_type> lock() const noexcept;
Lock and restore weak_ptr
Returns a shared_ptr with the information preserved by the weak_ptr object if it is not expired.

If the weak_ptr object has expired (including if it is empty), the function returns an empty shared_ptr (as if default-constructed).

Because shared_ptr objects count as an owner, this function locks the owned pointer, preventing it from being released (for at least as long as the returned object does not releases it).

This operation is executed atomically.

Parameters

none

Return value

If the object is weak_ptr::expired, a default-constructed shared_ptr object.
Otherwise, a shared_ptr object with the information preserved by the weak_ptr.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// weak_ptr::lock example
#include <iostream>
#include <memory>
int main () {
 std::shared_ptr<int> sp1,sp2;
 std::weak_ptr<int> wp;
 // sharing group:
 // --------------
 sp1 = std::make_shared<int> (20); // sp1
 wp = sp1; // sp1, wp
 sp2 = wp.lock(); // sp1, wp, sp2
 sp1.reset(); // wp, sp2
 sp1 = wp.lock(); // sp1, wp, sp2
 std::cout << "*sp1: " << *sp1 << '\n';
 std::cout << "*sp2: " << *sp2 << '\n';
 return 0;
}

Output:
*sp1: 20
*sp2: 20


See also

weak_ptr::reset
Reset pointer (public member function)
weak_ptr::expired
Check if expired (public member function)

AltStyle によって変換されたページ (->オリジナル) /