std::weak_ptr::swap(3)
π¦ std::weak_ptr::swap β C++ Standard Libary, section 3 π¦
okay so bestie, this is the std::weak_ptr::swap(3) page from the C++ Standard Libary manual, and it's a tiny little icon. no cap.
β¨ NAME β¨
std::weak_ptr::swap β and yes, the name is literally std::weak_ptr::swap. it's giving βI contain multitudes, but the multitudes are the same name.β π
πΈ Synopsis πΈ
void swap( weak_ptr& r ) noexcept; (since C++11)
This exchanges the stored pointer values and the ownerships of *this and r. Reference counts, if any, are not adjusted. π¨
bestie, read that last bit again: reference counts, if any, are not adjusted. it's not doing a little count dance for you. π
π Parameters π
rβ a smart pointer to exchange the contents with. that's the whole parameter. slay, simple. π«Ά
β Return value β
The return value is (none) β literally nothing comes back. it's a void moment, periodt. π
π¦ Example π¦
here's the example, kept exact because we do not play with code in this house. run it and vibe-check the output:
// Run this code
#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> sp1 = std::make_shared<Foo>(100);
std::shared_ptr<Foo> sp2 = std::make_shared<Foo>(200);
std::weak_ptr<Foo> wp1 = sp1;
std::weak_ptr<Foo> wp2 = sp2;
auto print = [&]()
{
auto p1 = wp1.lock();
auto p2 = wp2.lock();
std::cout << " p1=" << (p1 ? p1->print() : "nullptr");
std::cout << " p2=" << (p2 ? p2->print() : "nullptr") << '\n';
};
print();
wp1.swap(wp2);
print();
wp1.reset();
print();
wp1.swap(wp2);
print();
}
π Output π
Foo...
Foo...
p1=100 p2=200
p1=200 p2=100
p1=nullptr p2=100
p1=100 p2=nullptr
~Foo...
~Foo...
source/version is http://cppreference.com, date is 2024.06.10. stay swapped, bestie πβ¨
π¦ 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