std::swap(std::weak_ptr)(3)
π std::swap(std::weak_ptr) π
okay bestie, welcome to the C++ Standard Libary manual page for std::swap(std::weak_ptr) β yes, thatβs the whole name, and yes, itβs a mouthful. no cap. This is the group-chat explanation, but every fact is staying exactly where it belongs. β¨
π NAME π
std::swap(std::weak_ptr) β literally the page for std::swap(std::weak_ptr). Itβs giving βspecialized swap for weak pointersβ energy. π
πΈ Synopsis πΈ
Defined in header <memory>
template< class T >
(since C++11)
void swap( std::weak_ptr<T>& lhs, std::weak_ptr<T>& rhs ) noexcept;
This thing specializes the std::swap algorithm for std::weak_ptr. It swaps the contents of lhs and rhs, and it calls lhs.swap(rhs). π«Ά
π¦ Parameters π¦
lhs,rhsβ smart pointers whose contents to swap β¨
π Return value π
(none) β literally nothing comes back, bestie. It just does the swap. π
β Complexity β
Constant. no notes. just constant. π₯
π» Example π»
// 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();
std::swap(wp1, wp2);
print();
wp1.reset();
print();
std::swap(wp1, wp2);
print();
}
π Output π
Foo...
Foo...
p1=100 p2=200
p1=200 p2=100
p1=nullptr p2=100
p1=100 p2=nullptr
~Foo...
~Foo...
π See also π
swapβ swaps the values of two objects (function template)swapβ swaps the contents (public member function)
mwah π this cutie came from http://cppreference.com, dated 2024.06.10 β C++ Standard Libary manual, periodt. π«Ά
π¦ 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