命名空间
变体
操作

std::optional<T>::operator=

来自 cppreference.cn
< 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(/* see below */);
(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 = std::remove_cv_t<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. 换句话说,T 不能从任何类型(可能为 const 限定)的表达式 std::optional<U> 构造、转换或赋值

目录

[编辑] 参数

其他 - other
value - 要赋值给包含值的值

[编辑] 返回值

*this

[编辑] 异常

2-6) 抛出由 T 的构造函数或赋值运算符抛出的任何异常。如果抛出异常,*this(以及在 (2-5) 情况下的 other)的初始化状态保持不变,即如果对象包含值,则它仍然包含值,反之亦然。value 的内容以及 *thisother 的包含值取决于异常来源操作(复制构造函数、移动赋值等)的异常安全保证。
3) 具有以下特性:
noexcept 规范:  

[编辑] 注意

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

特性测试 标准 特性
__cpp_lib_optional 202106L (C++20)
(DR20)
完全 constexpr (1), (4-6)

[编辑] 示例

#include <iostream>
#include <optional>
 
int main()
{
    std::optional<const char*> s1 = "abc", s2; // constructor
    s2 = s1; // assignment
    s1 = "def"; // decaying assignment (U = char[4], T = const char*)
    std::cout << *s2 << ' ' << *s1 << '\n';
}

输出

abc def

[编辑] 缺陷报告

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

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

[编辑] 参阅

就地构造包含的值
(public member function) [编辑]