다음을 통해 공유


shared_ptr::swap

교체 2 shared_ptr 개체입니다.

void swap(shared_ptr& sp);

매개 변수

  • sp
    바꿔 볼 수 있는 공유 포인터입니다.

설명

멤버 함수는 원래 소유한 리소스를 벗어날 *this 이후에 소유한 sp, 및 원래 소유한 리소스 sp 이후에 소유한 *this.함수는 두 리소스에 대 한 참조 횟수 변경 되지 않고 예외를 throw 하지 않습니다.

예제

 

// std_tr1__memory__shared_ptr_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 Class

shared_ptr::operator=