Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::monostate — an explicit state without data

std::monostate is an empty type available through <variant>. It can represent an explicit state without data and, as the first std::variant alternative, enables default construction even when a later type has no default constructor.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

#include <variant>
std::monostate{};
std::variant<std::monostate, T> value;

std::monostate is an empty structure available through the <variant> header. Its objects represent a single state and always compare equal. The program assigns that state a meaning, such as “not set yet”; the type itself stores no application data.

The default constructor of std::variant initializes its first alternative, at index 0. Placing std::monostate first therefore lets the variant be default-constructed even if the next alternative has no default constructor. Placing it only at a later position does not fix an unavailable constructor for the first alternative.

A variant holding std::monostate still contains a valid value of one of its alternatives. This is not the valueless_by_exception() state, in which the variant contains no value. Including std::monostate does not automatically prevent the variant from losing its value because of an exception during other operations.

In the example, Item() is deleted, but state is created with std::monostate active. Calling emplace<Item>(42) replaces it with an Item, and assigning std::monostate{} restores the explicit state without data. When reading through std::get<Item>, the active alternative must be Item; otherwise, std::bad_variant_access is thrown.

Examples

#include <iostream>
#include <variant>

struct Item {
    int value;
    Item() = delete;
    explicit Item(int n) : value(n) {}
};

int main() {
    std::variant<std::monostate, Item> state;
    std::cout << std::boolalpha;
    std::cout << std::holds_alternative<std::monostate>(state) << '\n';
    std::cout << state.valueless_by_exception() << '\n';

    state.emplace<Item>(42);
    std::cout << std::get<Item>(state).value << '\n';

    state = std::monostate{};
    std::cout << state.index() << '\n';
}

Result

true
false
42
0

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources