std::swap(std::optional)

Header: <optional>

Overloads the std::swap algorithm for std::optional. Exchanges the state of lhs with that of rhs. Effectively calls lhs.swap(rhs).

# Declarations

template< class T >
void swap( std::optional<T>& lhs,
std::optional<T>& rhs ) noexcept(/* see below */);

(since C++17) (constexpr since C++20)

# Parameters

# Return value

(none)

# Notes

Feature-test macro Value Std Feature __cpp_lib_optional 202106L (C++20)(DR20) Fully constexpr

# Example

#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):");
}

# Defect reports

DRApplied toBehavior as publishedCorrect behavior
P2231R1C++20swap was not constexpr while the required operations can be constexpr in C++20made constexpr

# See also