std::optional<T>::reset
來自 cppreference.com
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 | 在 C++20 中,雖然非平凡析構在 constexpr 中是允許的,但 reset 不是 constexpr。 |
設為 constexpr |
[編輯] 參閱
賦值內容 (公共成員函式) |