public member function
<memory>

std::weak_ptr::operator=

weak_ptr& operator= (const weak_ptr& x) noexcept;
template <class U> weak_ptr& operator= (const weak_ptr<U>& x) noexcept;
template <class U> weak_ptr& operator= (const shared_ptr<U>& x) noexcept;
weak_ptr assignment
The object becomes part of the owning group of x, giving access to that object's assets until expired without taking ownership itself (and without increasing its use count).

If x is empty, the constructed weak_ptr is also empty.

If x is an alias, the weak_ptr preserves both the owned data and the stored pointer.

shared_ptr objects can be assigned to weak_ptr objects directly, but in order to assign a weak_ptr object to a shared_ptr it shall be done using member lock.

Parameters

x
An object of a weak_ptr or shared_ptr type.
U* shall be implicitly convertible to T* (where T is shared_ptr's template parameter).

Return value

*this

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::operator= 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> (10);    // 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: 10
*sp2: 10

See also