std::optional<T>:: reset
From cppreference.net
C++
Utilities library
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
std::optional
| Member functions | ||||
| Observers | ||||
| Iterators | ||||
|
(C++26)
|
||||
|
(C++26)
|
||||
| Monadic operations | ||||
|
(C++23)
|
||||
|
(C++23)
|
||||
|
(C++23)
|
||||
| Modifiers | ||||
|
optional::reset
|
||||
| Non-member functions | ||||
| Deduction guides | ||||
| Helper classes | ||||
| Helper objects | ||||
|
void
reset
(
)
noexcept
;
|
(自 C++17 起)
(自 C++20 起为 constexpr) |
|
若 * this 包含值,则通过 value ( ) . T :: ~T ( ) 的方式销毁该值。否则,不产生任何效果。
* this 在此调用后将不包含任何值。
目录 |
注释
| 功能测试宏 | 值 | 标准 | 功能特性 |
|---|---|---|---|
__cpp_lib_optional
|
202106L
|
(C++20)
(DR20) |
完全 constexpr |
示例
运行此代码
#include <iostream> #include <optional> struct A { std::string s; A(std::string str) : s(std::move(str)) { std::cout << " constructed\n"; } ~A() { std::cout << " destructed\n"; } A(const A& o) : s(o.s) { std::cout << " copy constructed\n"; } A(A&& o) : s(std::move(o.s)) { std::cout << " move constructed\n"; } A& operator=(const A& other) { s = other.s; std::cout << " copy assigned\n"; return *this; } A& operator=(A&& other) { s = std::move(other.s); std::cout << " move assigned\n"; return *this; } }; int main() { std::cout << "Create empty optional:\n"; std::optional<A> opt; std::cout << "Construct and assign value:\n"; opt = A("Lorem ipsum dolor sit amet, consectetur adipiscing elit nec."); std::cout << "Reset optional:\n"; opt.reset(); std::cout << "End example\n"; }
输出:
Create empty optional: Construct and assign value: constructed move constructed destructed Reset optional: destructed End example
缺陷报告
下列行为变更缺陷报告被追溯应用于先前发布的 C++ 标准。
| 缺陷报告 | 应用于 | 发布时的行为 | 正确行为 |
|---|---|---|---|
| P2231R1 | C++20 |
reset
不是 constexpr,而 C++20 允许在
constexpr
中进行非平凡析构
|
设为 constexpr |
参见
|
赋值内容
(公开成员函数) |