std::swap(std::shared_ptr)
來自 cppreference.com
< cpp | 記憶體 | shared ptr
定義於標頭檔案 <memory> |
||
template< class T > void swap( std::shared_ptr<T>& lhs, std::shared_ptr<T>& rhs ) noexcept; |
(C++11 起) | |
特化 std::shared_ptr 的 std::swap 演算法。交換 lhs 和 rhs 的內容。呼叫 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> p1 = std::make_shared<Foo>(100); std::shared_ptr<Foo> p2 = std::make_shared<Foo>(200); auto print = [&]() { std::cout << " p1=" << (p1 ? p1->print() : "nullptr"); std::cout << " p2=" << (p2 ? p2->print() : "nullptr") << '\n'; }; print(); std::swap(p1, p2); print(); p1.reset(); print(); std::swap(p1, p2); print(); }
輸出
Foo... Foo... p1=100 p2=200 p1=200 p2=100 ~Foo... p1=nullptr p2=100 p1=100 p2=nullptr ~Foo...
[編輯] 參閱
交換兩個物件的值 (函式模板) | |
交換內容 (public 成員函式) |