public member function
<memory>

std::weak_ptr::operator=

copy (1)
weak_ptr& operator= (const weak_ptr& x) noexcept;template <class U> weak_ptr& operator= (const weak_ptr<U>& x) noexcept;
from shared_ptr (2)
template <class U> weak_ptr& operator= (const shared_ptr<U>& x) noexcept;
copy (1)
weak_ptr& operator= (const weak_ptr& x) noexcept;template <class U> weak_ptr& operator= (const weak_ptr<U>& x) noexcept;
from shared_ptr (2)
template <class U> weak_ptr& operator= (const shared_ptr<U>& x) noexcept;
移動 (3)
weak_ptr& operator= (weak_ptr&& x) noexcept;template <class U> weak_ptr& operator= (weak_ptr<U>&& x) noexcept;
weak_ptr assignment
該物件成為x擁有組的一部分,從而在不擁有所有權(也不增加其use count)的情況下,提供對該物件資產的訪問,直到expired

如果x為空,則構造的weak_ptr也為空。

如果x是別名,則weak_ptr會保留擁有的資料儲存的指標

可以直接將shared_ptr物件賦值給weak_ptr物件,但為了將weak_ptr物件賦值給shared_ptr,應使用成員函式lock

引數

x
weak_ptrshared_ptr型別的物件。
U*應可隱式轉換為T*(其中Tshared_ptr的模板引數)。

返回值

*this

示例

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;
}

輸出
*sp1: 10
*sp2: 10


另見