Namespaces
Variants
Views
Actions

std::optional<T>::swap

From cppreference.com
< cpp‎ | utility‎ | optional
Revision as of 13:59, 29 June 2020 by Elbarto (Talk | contribs)

 
 
Utilities library
General utilities
Relational operators (deprecated in C++20)
 
 
void swap( optional& other ) noexcept(/* see below */);
(since C++17)

Swaps the contents with those of other.

  • If neither *this nor other contain a value, the function has no effect.
  • If only one of *this and other contains a value (let's call this object in and the other un), the contained value of un is direct-initialized from std::move(*in), followed by destruction of the contained value of in as if by in->T::~T(). After this call, in does not contain a value; un contains a value.
  • If both *this and other contain values, the contained values are exchanged by calling using std::swap; swap(**this, *other). T lvalues must satisfy Swappable.

The program is ill-formed if std::is_move_constructible_v<T> is false.

Contents

Parameters

other - the optional object to exchange the contents with

Return value

(none)

Exceptions

noexcept specification:  

In the case of thrown exception, the states of the contained values of *this and other are determined by the exception safety guarantees of swap of type T or T's move constructor, whichever is called. For both *this and other, if the object contained a value, it is left containing a value, and the other way round.

Example

#include <iostream>
#include <string>
#include <optional>
 
int main()
{
    std::optional<std::string> opt1("First example text");
    std::optional<std::string> opt2("2nd text");
 
    std::cout << "Before swap:\n";
    std::cout << "opt1 contains '" << opt1.value() << "'\n";
    std::cout << "opt2 contains '" << opt2.value() << "'\n";
 
    std::cout << "---SWAP---\n";
    opt1.swap(opt2);
 
    std::cout << "After swap:\n";
    std::cout << "opt1 contains '" << opt1.value() << "'\n";
    std::cout << "opt2 contains '" << opt2.value() << "'\n";
 
    // Swap with only 1 set
    opt1 = "Lorem ipsum dolor sit amet, consectetur tincidunt.";
    opt2.reset();
 
    std::cout << "\nBefore swap:\n";
    std::cout << "opt1 contains '" << opt1.value_or("") << "'\n";
    std::cout << "opt2 contains '" << opt2.value_or("") << "'\n";
 
    std::cout << "---SWAP---\n";
    opt1.swap(opt2);
 
    std::cout << "After swap:\n";
    std::cout << "opt1 contains '" << opt1.value_or("") << "'\n";
    std::cout << "opt2 contains '" << opt2.value_or("") << "'\n";
}

Output:

Before swap:
opt1 contains 'First example text'
opt2 contains '2nd text'
---SWAP---
After swap:
opt1 contains '2nd text'
opt2 contains 'First example text'
 
Before swap:
opt1 contains 'Lorem ipsum dolor sit amet, consectetur tincidunt.'
opt2 contains ''
---SWAP---
After swap:
opt1 contains ''
opt2 contains 'Lorem ipsum dolor sit amet, consectetur tincidunt.'

See also

specializes the std::swap algorithm
(function template) [edit]