std::shared_ptr::swap - cppreference.com (original) (raw)
Exchanges the stored pointer values and the ownerships of *this and r. Reference counts, if any, are not adjusted.
Run this code
#include
#include
#include
struct Foo
{
Foo(int _val) : val(_val) { std::cout << "Foo...\n"; }
Foo() { std::cout << "Foo...\n"; }
std::string print() { return std::to_string(val); }
int val;
};
int main()
{
std::shared_ptr p1 = std::make_shared(100);
std::shared_ptr p2 = std::make_shared(200);
auto print = &
{
std::cout << " p1=" << (p1 ? p1->print() : "nullptr");
std::cout << " p2=" << (p2 ? p2->print() : "nullptr") << '\n';
};
print();
p1.swap(p2);
print();
p1.reset();
print();
p1.swap(p2);
print();
}
Output:
Foo... Foo... p1=100 p2=200 p1=200 p2=100 ~Foo... p1=nullptr p2=100 p1=100 p2=nullptr ~Foo...