std::experimental::optional<T>::operator=
来自 cppreference.cn
< cpp | experimental | optional
optional& operator=( std::experimental::nullopt_t ) noexcept; |
(1) | (library fundamentals TS) |
optional& operator=( const optional& other ); |
(2) | (library fundamentals TS) |
optional& operator=( optional&& other ) noexcept(/* see below */); |
(3) | (library fundamentals TS) |
template< class U > optional& operator=( U&& value ); |
(4) | (library fundamentals TS) |
将 *this 的内容替换为 other 的内容。
1) 如果在调用之前 *this 包含值,则通过调用其析构函数(如同通过 val->T::~T())销毁包含的值。*this 在此调用后不包含值。
2,3) 赋值 other 的状态。
- 如果 *this 和 other 都不包含值,则此函数无效。
- 如果 *this 包含值,但 other 不包含值,则通过调用其析构函数来销毁包含的值。*this 在调用后不包含值。
- 如果 other 包含值,则取决于 *this 是否包含值,包含的值要么从 *other (2) 或 std::move(*other) (3) 直接初始化 或赋值。请注意,已移动来源的可选对象仍然包含值。
4) 仅衰退完美转发赋值:取决于调用之前 *this 是否包含值,包含的值要么从 std::forward<U>(value) 直接初始化,要么从 std::forward<U>(value) 赋值。除非 std::is_same<std::decay_t<U>, T>::value 为 true,否则此函数不参与重载解析。
目录 |
[编辑] 参数
other | - | 另一个 optional 对象,其包含的值将被赋值 |
value | - | 要赋值给包含的值 |
类型要求 | ||
-为了使用重载 (2),T 必须满足 CopyAssignable 和 CopyConstructible 的要求。 | ||
-为了使用重载 (3),T 必须满足 MoveAssignable 和 MoveConstructible 的要求。 |
[编辑] 返回值
*this
[编辑] 异常
2-4) 抛出
(3) 具有以下
T
的构造函数或赋值运算符抛出的任何异常。如果抛出异常,则 *this (以及 (2) 的情况下的 other)的初始化状态保持不变,即,如果对象包含值,则它仍然包含值,反之亦然。value 的内容以及 *this 和 other 的包含值取决于异常来源操作的异常安全保证(复制构造函数、移动赋值等)。(3) 具有以下
noexcept
声明noexcept 规范:
noexcept(std::is_nothrow_move_assignable<T>::value && std::is_nothrow_move_constructible<T>::value)
[编辑] 注解
可选对象 op
可以通过 op = {}; 和 op = nullopt; 变成空的可选对象。
[编辑] 示例
运行此代码
#include <experimental/optional> #include <iostream> int main() { std::experimental::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
[编辑] 参见
就地构造包含的值 (公共成员函数) |