• Class / Function / Type

      std::
    • Header file

      <>
    • Other / All

    最終更新日時(UTC):
    が更新

    履歴 編集

    function
    <memory>

    std::weak_ptr::operator=

    weak_ptr& operator=(const weak_ptr& r) noexcept;      // (1)
    
    template <class Y>
    weak_ptr& operator=(const weak_ptr<Y>& r) noexcept;   // (2)
    
    template <class Y>
    weak_ptr& operator=(const shared_ptr<Y>& r) noexcept; // (3)
    
    weak_ptr& operator=(weak_ptr&& r) noexcept;           // (4) C++14
    
    template <class Y>
    weak_ptr& operator=(weak_ptr<Y>&& r) noexcept;        // (5) C++14
    

    概要

    • (1) : *thisの現在の監視を停止し、rの監視対象を新たに監視する。
    • (2) : *thisの現在の監視を停止し、変換可能なweak_ptrオブジェクトrの監視対象を新たに監視する。
    • (3) : *thisの現在の監視を停止し、新たにrを監視する。
    • (4) : *thisの現在の監視を停止し、rの監視対象を*thisに移動する。
    • (5) : *thisの現在の監視を停止し、変換可能なweak_ptrオブジェクトrの監視対象を*thisに移動する。

    効果

    • (1), (2), (3) : 以下と等価の効果を持つ。

    weak_ptr(r).swap(*this)
    

    • (4), (5) : 以下と等価の効果を持つ。

    weak_ptr(move(r)).swap(*this)
    

    戻り値

    *this

    例外

    投げない

    #include <cassert>
    #include <iostream>
    #include <memory>
    
    int main()
    {
      // (1)
      // 他のweak_ptrオブジェクトの監視対象を、新たに監視する
      std::shared_ptr<int> sp1(new int(3));
      std::weak_ptr<int> wp1_org = sp1; // wp1_orgはsp1を監視する
      std::weak_ptr<int> wp1;
      wp1 = wp1_org; // wp1はwp1_orgの監視対象を監視する
    
      if (std::shared_ptr<int> r = wp1.lock()) {
        std::cout << *r << std::endl;
      }
    
      // (2)
      // 他の変換可能なweak_ptrオブジェクトの監視対象を、新たに監視する
      std::shared_ptr<int> sp2(new int(3));
      std::weak_ptr<int> wp2_org = sp2;
      std::weak_ptr<void> wp2;
      wp2 = wp2_org;
    
      if (std::shared_ptr<int> r = std::static_pointer_cast<int>(wp2.lock())) {
        std::cout << *r << std::endl;
      }
    
      // (3)
      // shared_ptrオブジェクトを新たに監視する
      std::shared_ptr<int> sp3(new int(3));
      std::weak_ptr<int> wp3;
      wp3 = sp3;
    
      if (std::shared_ptr<int> r = wp3.lock()) {
        std::cout << *r << std::endl;
      }
    
      // (4)
      // weak_ptrオブジェクトの監視対象を移動する
      std::shared_ptr<int> sp4(new int(3));
      std::weak_ptr<int> wp4_org = sp4;
      std::weak_ptr<int> wp4;
      wp4 = std::move(wp4_org);
    
      if (std::shared_ptr<int> r = wp4.lock()) {
        std::cout << *r << std::endl;
      }
    
      // (5)
      // 変換可能なweak_ptrオブジェクトの監視対象を移動する
      std::shared_ptr<int> sp5(new int(3));
      std::weak_ptr<int> wp5_org = sp5;
      std::weak_ptr<void> wp5;
      wp5 = std::move(wp5_org);
    
      if (std::shared_ptr<int> r = std::static_pointer_cast<int>(wp5.lock())) {
        std::cout << *r << std::endl;
      }
    }
    

    出力

    3
    3
    3
    3
    3
    

    バージョン

    言語

    • C++11

    処理系

    参照