std::shared_ptr::swap(3)
π std::shared_ptr::swap β bestie's guide to the glow-up swap
okay so real talk, this one is from the C++ Standard Libary man pages (manual section 3, std::shared_ptr::swap(3)), and it's genuinely one of the most satisfying little functions ever. like, no cap, it's giving "trading friendship bracelets" energy. π«Ά
β¨ NAME β¨
std::shared_ptr::swap β literally std::shared_ptr::swap, that's the whole name, she's not hiding anything π
π¦ Synopsis π¦
void swap( shared_ptr& r ) noexcept; (since C++11)
so what she does: she exchanges the stored pointer values and the ownerships of *this and r. that's it. that's the whole vibe. β¨
π¨ important caveat bestie: reference counts, if any, are not adjusted. like, the counts don't get touched at all. she's just swapping who holds what β she is not doing any behind-the-scenes math. iykyk.
and yes, she's noexcept β she will NOT throw at you, she's a reliable queen π
π Parameters π
rβ the smart pointer you wanna exchange contents with πΈ
π Return value π
none. zero. nada. she does the thing and dips. (none) π
π₯ Example π₯
run this code, it's so cute, watch the destructor messages roll in:
#include <iostream>
#include <memory>
#include <string>
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<Foo> p1 = std::make_shared<Foo>(100);
std::shared_ptr<Foo> p2 = std::make_shared<Foo>(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...
look at that little dance π§ β p1 and p2 trading places, then p1.reset() doing her thing (rip ~Foo..., you served), then one more swap and they've traded back. main character energy from start to finish π
π tiny note to self: the~Foo...on line 5 is the destructor firing for the100object whenp1.reset()drops ownership. iconic. that's it, that's the lesson.
source: http://cppreference.com Β· version date 2024.06.10 β mwah, love u, go swap some smart pointers responsibly πππ
π¦ where this page comes from
- nixpkgs unstable: stdman 2024.07.05
- opensuse-leap 16.0: stdman 2024.07.05-bp160.1.9 Β· MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms