名稱空間
變體
操作

std::swap(std::weak_ptr)

來自 cppreference.com
< cpp‎ | memory‎ | weak ptr
 
 
記憶體管理庫
(僅作說明*)
未初始化記憶體演算法
(C++17)
(C++17)
(C++17)
受約束的未初始化
記憶體演算法
C 庫

分配器
記憶體資源
垃圾回收支援
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
未初始化儲存
(直到 C++20*)
(直到 C++20*)
顯式生命週期管理
 
 
定義於標頭檔案 <memory>
template< class T >
void swap( std::weak_ptr<T>& lhs, std::weak_ptr<T>& rhs ) noexcept;
(C++11 起)

std::weak_ptr 特化 std::swap 演算法。交換 lhsrhs 的內容。呼叫 lhs.swap(rhs)


目錄

[編輯] 引數

lhs, rhs - 要交換內容的智慧指標

[編輯] 返回值

(無)

[編輯] 複雜度

常數時間。

[編輯] 示例

#include <iostream>
#include <memory>
#include <string>
 
struct Foo {
    Foo(int _val) : val(_val) { std::cout << "Foo...\n"; }
    ~Foo() { std::cout << "~Foo...\n"; }
    std::string print() { return std::to_string(val); }
    int val;
};
 
int main()
{
    std::shared_ptr<Foo> sp1 = std::make_shared<Foo>(100);
    std::shared_ptr<Foo> sp2 = std::make_shared<Foo>(200);
    std::weak_ptr<Foo> wp1 = sp1;
    std::weak_ptr<Foo> wp2 = sp2;
    auto print = [&]() {
        auto p1 = wp1.lock();
        auto p2 = wp2.lock();
        std::cout << " p1=" << (p1 ? p1->print() : "nullptr");
        std::cout << " p2=" << (p2 ? p2->print() : "nullptr") << '\n';  
    };
    print();
 
    std::swap(wp1, wp2);
    print();
 
    wp1.reset();
    print();
 
    std::swap(wp1, wp2);
    print();   
}

輸出

Foo...
Foo...
 p1=100 p2=200
 p1=200 p2=100
 p1=nullptr p2=100
 p1=100 p2=nullptr
~Foo...
~Foo...

[編輯] 參閱

交換兩個物件的值
(函式模板) [編輯]
交換內容
(公共成員函式) [編輯]