次の方法で共有


swap 関数 <memory>

2 つの shared_ptr オブジェクトまたは weak_ptr オブジェクトを交換します。

template<class Ty, class Other>
    void swap(shared_ptr<Ty>& left, shared_ptr<Other>& right);
template<class Ty, class Other>
    void swap(weak_ptr<Ty>& left, weak_ptr<Other>& right);

パラメーター

  • Ty
    左辺の共有/ウィーク ポインターによって制御される型。

  • Other
    右辺の共有/ウィーク ポインターによって制御される型。

  • left
    左辺の共有/ウィーク ポインター。

  • right
    右辺の共有/ウィーク ポインター。

解説

このテンプレート関数は、left.swap(right) を呼び出します。

使用例

 

// std_tr1__memory__swap.cpp 
// compile with: /EHsc 
#include <memory> 
#include <iostream> 
 
struct deleter 
    { 
    void operator()(int *p) 
        { 
        delete p; 
        } 
    }; 
 
int main() 
    { 
    std::shared_ptr<int> sp1(new int(5)); 
    std::shared_ptr<int> sp2(new int(10)); 
    std::cout << "*sp1 == " << *sp1 << std::endl; 
 
    sp1.swap(sp2); 
    std::cout << "*sp1 == " << *sp1 << std::endl; 
 
    swap(sp1, sp2); 
    std::cout << "*sp1 == " << *sp1 << std::endl; 
    std::cout << std::endl; 
 
    std::weak_ptr<int> wp1(sp1); 
    std::weak_ptr<int> wp2(sp2); 
    std::cout << "*wp1 == " << *wp1.lock() << std::endl; 
 
    wp1.swap(wp2); 
    std::cout << "*wp1 == " << *wp1.lock() << std::endl; 
 
    swap(wp1, wp2); 
    std::cout << "*wp1 == " << *wp1.lock() << std::endl; 
 
    return (0); 
    } 
 
  

必要条件

ヘッダー : <memory>

名前空間: std

参照

関連項目

shared_ptr クラス

weak_ptr クラス