Spec-Zone.ru › C++

std::expected<T,E>::swap

Основной шаблон
constexpr void swap( expected& other ) noexcept(/* see below */);
(1) (начиная с C++23)
Частичная специализация void
constexpr void swap( expected& other ) noexcept(/* see below */);
(2) (начиная с C++23)

Обменивает содержимое с содержимым other.

1) Содержащиеся значения обмениваются следующим образом:
Значение
has_value()
Значение other.has_value()
true false
true usingstd::swap;
swap(val,rhs.val);
см. ниже
false other.swap(*this); usingstd::swap;
swap(unex,rhs.unex);
Если has_value() равно true, а other.has_value() равно false, то эквивалентно:

// Case 1: the move constructions of unexpected values are non-throwing:
// “other.unex” will be restored if the construction of “other.val” fails
ifconstexpr(std::is_nothrow_move_constructible_v<E>)
{
    Etemp(std::move(other.unex));
    std::destroy_at(std::addressof(other.unex));
    try
    {
        std::construct_at(std::addressof(other.val),std::move(val));// may throw
        std::destroy_at(std::addressof(val));
        std::construct_at(std::addressof(unex),std::move(temp));
    }
    catch(...)
    {
        std::construct_at(std::addressof(other.unex),std::move(temp));
        throw;
    }
}
// Case 2: the move constructions of expected values are non-throwing:
// “this->val” will be restored if the construction of “this->unex” fails
else
{
    Ttemp(std::move(val));
    std::destroy_at(std::addressof(val));
    try
    {
        std::construct_at(std::addressof(unex),std::move(other.unex));// may throw 
        std::destroy_at(std::addressof(other.unex));
        std::construct_at(std::addressof(other.val),std::move(temp));
    }
    catch(...)
    {
        std::construct_at(std::addressof(val),std::move(temp));
        throw;
    }
}
has_val =false;
rhs.has_val =true;

Эта перегрузка участвует в разрешении перегрузки, только если все следующие значения являются true:
  • std::is_swappable_v<T>
  • std::is_swappable_v<E>
  • std::is_move_constructible_v<T> && std::is_move_constructible_v<E>
  • std::is_nothrow_move_constructible_v<T> || std::is_nothrow_move_constructible_v<E>
2) Неожиданные значения обмениваются следующим образом:
Значение
has_value()
Значение other.has_value()
true false
true usingstd::swap;
swap(val,rhs.val);
std::construct_at(std::addressof(unex),                  std::move(rhs.unex));std::destroy_at(std::addressof(rhs.unex));has_val = false;rhs.has_val = true;
false other.swap(*this); usingstd::swap;
swap(unex, rhs.unex);
Эта перегрузка участвует в разрешении перегрузки, только если std::is_swappable_v<E> и std::is_move_constructible_v<E> оба являются true.

Параметры

other - объект expected, с которым обменивается содержимое

Исключения

1)
noexcept спецификация:
noexcept(
    std::is_nothrow_move_constructible_v<T> && std::is_nothrow_swappable_v<T> &&
    std::is_nothrow_move_constructible_v<E> && std::is_nothrow_swappable_v<E>
)
2)
noexcept спецификация:
noexcept(
    std::is_nothrow_move_constructible_v<E> && std::is_nothrow_swappable_v<E>
)

Пример

#include <expected>
#include <iostream>
#include <string>

using Ex = std::expected<std::string, int>;

void show(const Ex& ex1, const Ex& ex2)
{
    for (int i{}; i < 2; ++i)
    {
        std::cout << (i ? "ex2" : "ex1");
        if (const Ex& ex = (i ? ex2 : ex1); ex.has_value())
            std::cout << ".has_value() = " << *ex << '\n';
        else
            std::cout << ".error() = " << ex.error() << '\n';
    }
}

int main()
{
    Ex ex1("\N{CAT FACE}");
    Ex ex2{"\N{GREEN HEART}"};
    show(ex1, ex2);
    ex1.swap(ex2);
    std::cout << "ex1.swap(ex2);\n";
    show(ex1, ex2);
    std::cout << '\n';

    ex2 = std::unexpected(13);
    show(ex1, ex2);
    std::cout << "ex1.swap(ex2);\n";
    ex1.swap(ex2);
    show(ex1, ex2);
    std::cout << '\n';

    ex2 = std::unexpected(19937);
    show(ex1, ex2);
    std::cout << "ex1.swap(ex2);\n";
    ex1.swap(ex2);
    show(ex1, ex2);
}

Вывод:

ex1.has_value() = 🐱
ex2.has_value() = 💚
ex1.swap(ex2);
ex1.has_value() = 💚
ex2.has_value() = 🐱

ex1.has_value() = 💚
ex2.error() = 13
ex1.swap(ex2);
ex1.error() = 13
ex2.has_value() = 💚

ex1.error() = 13
ex2.error() = 19937
ex1.swap(ex2);
ex1.error() = 19937
ex2.error() = 13

См. также

swap(std::expected)
(C++23)
специализация алгоритма std::swap
(функция)

© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
https://en.cppreference.com/cpp/utility/expected/swap

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API