std::optional::value(3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

std::optional::value πŸ’…βœ¨

okay so this is std::optional::value from the C++ Standard Libary manual β€” yes, β€œLibary” with one R, the typo is canon, don’t come for me πŸ’€. It’s giving β€œchecked access bestie” and honestly? Obsessed.

NAME πŸŽ€

std::optional::value β€” std::optional::value. Yep, the name is the name, twice, because why not. Iconic. Periodt.

✨ Synopsis ✨

constexpr T& value() &;               (1) (since C++17)
constexpr const T& value() const &;
constexpr T&& value() &&;             (2) (since C++17)
constexpr const T&& value() const &&;

If *this contains a value, it returns a reference to the contained value.

Otherwise, it throws a std::bad_optional_access exception. That’s the whole plot, no cap 😭.

Parameters 🫢

(none) β€” literally none, bestie. Zero. Nada. 🧚

Return value πŸ’–

A reference to the contained value. Slay.

Exceptions 🚨

std::bad_optional_access if *this does not contain a value. So like, it will absolutely call you out if you try to access nothing, fr fr.

Notes πŸ“

The dereference operator operator*() does not check if this optional contains a value, which may be more efficient than value(). That’s the note. That’s the vibe. Lowkey important, highkey iconic. πŸ’…

Example 🌸

Here’s the code, bestie β€” run it and see for yourself:

// Run this code

#include <iostream>
#include <optional>

int main()
{
    std::optional<int> opt = {};

    try
    {
        [[maybe_unused]] int n = opt.value();
    }
    catch(const std::bad_optional_access& e)
    {
        std::cout << e.what() << '\n';
    }

    try
    {
        opt.value() = 42;
    }
    catch(const std::bad_optional_access& e)
    {
        std::cout << e.what() << '\n';
    }

    opt = 43;
    std::cout << *opt << '\n';

    opt.value() = 44;
    std::cout << opt.value() << '\n';
}

Output: πŸ’¬

bad optional access
bad optional access
43
44

πŸ‘€ See also πŸ‘€

  • value_or β€” returns the contained value if available, another value otherwise (public member function)
  • operator-> β€” accesses the contained value
  • operator* β€” (public member function)
  • bad_optional_access β€” exception indicating checked access to an optional that doesn’t contain a value (C++17) (class)

okay bye bestie 🫢 the source is http://cppreference.com, the date on this one is 2024.06.10, and yeah β€” it’s std::optional::value(3). mwah πŸ’‹βœ¨

πŸ“¦ where this page comes from