1.概要
c++ 智能指针 交换函数实验
交换后,两个指针管理的目标对象会发生交换
sh_ptr1.swap(sh_ptr2);
2.代码
#include <iostream>
using namespace std;int main()
{shared_ptr<int> sh_ptr1 = std::make_shared<int>(5);shared_ptr<int> sh_ptr2 = std::make_shared<int>(6);//交换前cout << "-- pre-switch ------------------------------------------\n";cout << "*sh_ptr1 == " << *sh_ptr1 << endl;cout << "*sh_ptr2 == " << *sh_ptr2 << endl;swap(sh_ptr1, sh_ptr2);//sh_ptr1.swap(sh_ptr2);//交换后cout << "-- After exchange ------------------------------------------\n";cout << "*sh_ptr1 == " << *sh_ptr1 << endl;cout << "*sh_ptr2 == " << *sh_ptr2 << endl;std::cout << "Hello World!\n";
}
3.运行结果
-- pre-switch ------------------------------------------
*sh_ptr1 == 5
*sh_ptr2 == 6
-- After exchange ------------------------------------------
*sh_ptr1 == 6
*sh_ptr2 == 5
Hello World!