std::swap(std::optional)(3)
π NAME π
okay so this page is std::swap(std::optional) β like, literally std::swap(std::optional), bestie β and it comes from the C++ Standard Libary manual. yes, that's the manual name up top, folded in all cute so you don't have to read a crusty header line. π«Ά
β¨ Synopsis β¨
it's defined in the header <optional>, and here's the signature, line breaks and all, no cap:
Defined in header <optional>
template< class T >
void swap( std::optional<T>& lhs, (since
C++17)
(constexpr
since C++20)
std::optional<T>& rhs ) noexcept(/* see below
*/);
This overloads the std::swap algorithm for std::optional. it exchanges the state of lhs with that of rhs, and effectively calls lhs.swap(rhs). iconic. π
This overload participates in overload resolution only if std::is_move_constructible_v<T> and std::is_swappable_v<T> are both true. both of them. no exceptions to that little rule, bestie. β¨
π«Ά Parameters π«Ά
lhs,rhsβ optional objects whose states to swap. yes, both of them, swapping their little states. π¦
πΈ Return value πΈ
(none) β literally nothing comes back. it's giving "the swap was the point". π
π₯ Exceptions π₯
noexcept specification:
noexcept(noexcept(lhs.swap(rhs)))
that's the whole exception vibe, periodt. π
π Example π
// Run this code
#include <iostream>
#include <optional>
#include <string>
int main()
{
std::optional<std::string> a{"ββββββ"}, b{"ββββββ"};
auto print = [&](auto const& s)
{
std::cout << s << "\t"
"a = " << a.value_or("(null)") << " "
"b = " << b.value_or("(null)") << '\n';
};
print("Initially:");
std::swap(a, b);
print("swap(a, b):");
a.reset();
print("\n""a.reset():");
std::swap(a, b);
print("swap(a, b):");
}
π Output π
Initially: a = ββββββ b = ββββββ
swap(a, b): a = ββββββ b = ββββββ
a.reset(): a = (null) b = ββββββ
swap(a, b): a = ββββββ b = (null)
π§ Defect reports π§
The following behavior-changing defect reports were applied retroactively to previously published C++ standards. history said "let's fix that" and honestly? slay. π₯
P2231R1β applied to C++20.- Behavior as published:
swapwas notconstexprwhile the required operations can beconstexprin C++20. - Correct behavior: made
constexpr.
- Behavior as published:
π See also π
swapβ exchanges the contents (public member function). it's a public member function, iykyk. π
π Category π
* conditionally noexcept
source/version and date, cute sign-off style: this page is from http://cppreference.com, dated 2024.06.10, and it's page std::swap(std::optional)(3). bye bestie, go swap something 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