交换两个 shared_ptr 对象。
void swap(shared_ptr& sp);
参数
- sp
交换的共享指针。
备注
成员函数使资源最初自己的由 sp随后所属 *this 和 sp 最初属于自己的资源随后自己的 *this。 函数不更改两种资源的引用计数,并且它永远不引发任何异常。
示例
// 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);
}
要求
页眉: <内存>
命名空间: std