Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::optional::operator bool — checking for a value

`if (opt)` checks whether a `std::optional` contains a value, not whether that value is true. An index of `0` and a flag of `false` both count as present.

Version: ISO C++23; implementation support may vary

Syntax

#include <optional>

// Members of std::optional<T>:
constexpr explicit operator bool() const noexcept;
constexpr bool has_value() const noexcept;

std::optional::operator bool is an explicit conversion member of std::optional<T> in <optional>. Like opt.has_value(), it returns true exactly when opt contains a value. Both functions have been available since C++17, are callable on const objects, do not throw (noexcept), and can be used in constant expressions (constexpr) when the context permits.

explicit still allows contextual conversion to bool, so if (opt) and !opt work. Copy-initialization with bool present = opt; is ill-formed. To store the result, use bool present = opt.has_value(); or bool present = static_cast<bool>(opt);.

Keep presence separate from content. std::optional<int>{0} can hold a valid zero-based index, and std::optional<bool>{false} holds false; both pass the presence test. To test that a flag is both present and true, use if (flag && *flag). Built-in && evaluates the right operand only if the left operand is true.

Use *opt or opt->member only while opt still contains a value. In C++23, accessing an empty optional this way has undefined behavior; opt.value() instead throws std::bad_optional_access. A presence check does not extend the contained value's lifetime: for example, reset() destroys the value and invalidates references to it.

Examples

#include <iostream>
#include <optional>

int main() {
    const std::optional<int> index{0};
    const std::optional<int> missing;
    const std::optional<bool> flag{false};

    if (index) {
        std::cout << "index: " << *index << '\n';
    }
    if (!missing) {
        std::cout << "index missing\n";
    }
    if (flag) {
        std::cout << "stored flag: " << std::boolalpha << *flag << '\n';
    }
}

Result

index: 0
index missing
stored flag: false

The output distinguishes index `0` from a missing index. `if (flag)` takes the branch even though the value read through `*flag` is `false`.

Related lessons

  • C++ · Lesson 48 · Advanced · Version: 3
  • C++ · Lesson 51 · Advanced · Version: 3

Sources