std::optional<T>::operator=

来自cppreference.com
< cpp‎ | utility‎ | optional
 
 
 
 
optional& operator=( std::nullopt_t ) noexcept;
(1)(C++17 起)
(C++20 起为 constexpr)
constexpr optional& operator=( const optional& other );
(2)(C++17 起)
constexpr optional& operator=
    ( optional&& other ) noexcept(/* 见下文 */);
(3)(C++17 起)
template< class U >
optional& operator=( const optional<U>& other );
(4)(C++17 起)
(C++20 起为 constexpr)
template< class U >
optional& operator=( optional<U>&& other );
(5)(C++17 起)
(C++20 起为 constexpr)
template< class U = T >
optional& operator=( U&& value );
(6)(C++17 起)
(C++20 起为 constexpr)

other 的内容替换 *this 的内容。

1) 如果 *this 含值,那么通过调用 val ->T::~T() 来销毁包含的值;否则没有效果。此调用后 *this 不含值。
2-5) 赋值 other 的状态。此调用后 has_value() 会返回 other.has_value()
效果*this 含值*this 不含值
other 含值
  • 对于重载 (2,4),将 *other 赋给包含的值
  • 对于重载 (3,5),将 std::move(*other) 赋给包含的值
  • 对于重载 (2,4),以 *other 直接非列表初始化包含的值
  • 对于重载 (3,5),以 std::move(*other) 直接非列表初始化包含的值
other 不含值通过调用 val ->T::~T() 来销毁包含的值没有效果
2) 如果 std::is_copy_constructible_v<T>std::is_copy_assignable_v<T>false,那么此赋值运算符被定义为弃置。
如果 std::is_trivially_copy_constructible_v<T>std::is_trivially_copy_assignable_v<T>std::is_trivially_destructible_v<T> 都是 true,那么此赋值运算符是平凡的。
3) 此重载只有在 std::is_move_constructible_v<T>std::is_move_assignable_v<T> 都是 true 时才会参与重载决议。
如果 std::is_trivially_move_constructible_v<T>std::is_trivially_move_assignable_v<T>std::is_trivially_destructible_v<T> 都是 true,那么此赋值运算符是平凡的。
4,5) 这些重载只有在满足以下所有条件时才会参与重载决议:
6) 如果 *this 含值,那么将 std::forward<U>(value) 赋给包含的值;否则以 std::forward<U>(value) 直接非列表初始化包含的值。此调用后 *this 含值。
此重载只有在满足以下所有条件时才会参与重载决议:
  1. 也就是说,从任何(可有 const 限定的)std::optional<U> 类型的表达式都不能构造,转换到或赋值到 T

参数

other-要赋值其所含值的 optional 对象
value-要赋值给所含值的值

返回值

*this

异常

2-6) 抛出 T 的构造函数或赋值运算符所抛的任何异常。如果抛出异常,那么 *this(还有情况 (2-5)other)的初始化状态不改变,即对象含值的情况下它仍然含值,反之亦然。value*thisother 所含有的值的内容依赖于异常来源操作(复制构造函数、移动构造函数等)的异常安全保证。
3) 拥有下列
noexcept 说明:  

注解

optional 对象 op 可以通过 op = {};op = nullopt; 变成空 optional。第一个表达式以 {} 构造空的 optional 对象并将它赋值给 op

功能特性测试标准功能特性
__cpp_lib_optional202106L(C++20)
(DR20)
完全 constexpr (1), (4-6)

示例

#include <iostream>
#include <optional>
 
int main()
{
    std::optional<const char*> s1 = "abc", s2; // 构造函数
    s2 = s1; // 赋值
    s1 = "def"; // 衰变赋值(U = char[4], T = const char*)
    std::cout << *s2 << ' ' << *s1 << '\n';
}

输出:

abc def

缺陷报告

下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。

缺陷报告应用于出版时的行为正确行为
LWG 3886C++17重载 (6) 的默认模板实参是 T改成 std::remove_cv_t<T>
P0602R4C++17即使底层操作平凡,复制/移动赋值运算符亦可能不平凡要求传播平凡性
P2231R1C++20重载 (1,4-6) 不是 constexpr使之为 constexpr

参阅

原位构造所含值
(公开成员函数)