std::swap(std::unique_ptr)(3)
π std::swap(std::unique_ptr)(3) π
Okay bestie, this is the std::swap(std::unique_ptr) page from the C++ Standard Libary manual (yes, βLibaryβ is literally how the header spells it β we donβt fix, we preserve π ). Buckle up.
πΈ NAME πΈ
std::swap(std::unique_ptr) β aka std::swap(std::unique_ptr). Thatβs the name, thatβs the whole name, no cap. π
β¨ Synopsis β¨
The original synopsis is formatted a little feral, so here it is exactly:
Defined in header <memory>
template< class T, class D > (since
C++11)
void swap( std::unique_ptr<T, D>& lhs, std::unique_ptr<T,
(constexpr since C++23)
D>& rhs ) noexcept;
Translation: this specializes the std::swap algorithm for std::unique_ptr. It swaps the contents of lhs and rhs. And how does it do it? It calls lhs.swap(rhs). Slay. β¨
π¨ Vibe check: this function does not participate in overload resolution unlessstd::is_swappable_v<D>istrue(since C++17). Thatβs important, bestie β donβt skip it.
π Parameters π
lhs,rhsβ the smart pointers whose contents are getting swapped. π«Ά
π Return value π
None. Literally (none). Itβs giving void energy, and honestly thatβs the point. π
β Complexity β
Constant. Thatβs it, thatβs the complexity. No cap. β
π¦ Example π¦
// Run this code β yes, thatβs literally what the page says, so run it, bestie:
#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::unique_ptr<Foo> p1 = std::make_unique<Foo>(100);
std::unique_ptr<Foo> p2 = std::make_unique<Foo>(200);
auto print = [&]() {
std::cout << " p1=" << (p1 ? p1->print() : "nullptr");
std::cout << " p2=" << (p2 ? p2->print() : "nullptr") << '\n';
};
print();
std::swap(p1, p2);
print();
p1.reset();
print();
std::swap(p1, p2);
print();
}
π₯ Output π₯
Foo...
Foo...
p1=100 p2=200
p1=200 p2=100
~Foo...
p1=nullptr p2=100
p1=100 p2=nullptr
~Foo...
π See also π
swapβ swaps the values of two objects. (function template)swapβ swaps the contents. (public member function)
So thatβs the whole page, bestie. Source: http://cppreference.com; date: 2024.06.10; manual page: std::swap(std::unique_ptr)(3). Mwah ππ
π¦ 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