Namespaces
Variants

std::optional<T>:: reset

From cppreference.net
Utilities library
void reset ( ) noexcept ;
(C++17以降)
(constexpr C++20以降)

* 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++規格に対して遡及的に適用されました。

DR 適用対象 公開時の動作 正しい動作
P2231R1 C++20 reset はconstexprではなかったが、C++20では非自明な破棄が constexpr で許可されている constexpr 化された

関連項目

内容を代入
(public member function)