This topic has not yet been rated - Rate this topic

swap Function <memory>

Swap two shared_ptr or weak_ptr objects.

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

The type controlled by the left shared/weak pointer.

Other

The type controlled by the right shared/weak pointer.

left

The left shared/weak pointer.

right

The right shared/weak pointer.

The template functions call 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::tr1::shared_ptr<int> sp1(new int(5)); 
    std::tr1::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::tr1::weak_ptr<int> wp1(sp1); 
    std::tr1::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); 
    } 
 
*sp1 == 5 *sp1 == 10 *sp1 == 5 *wp1 == 5 *wp1 == 10 *wp1 == 5

Header: <memory>

Namespace: std::tr1

Did you find this helpful?
(1500 characters remaining)

Community Additions

ADD
© 2013 Microsoft. All rights reserved.