std::optional::value(3)
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 valueoperator*β (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
- nixpkgs unstable: stdman 2024.07.05
- opensuse-leap 16.0: stdman 2024.07.05-bp160.1.9 Β· MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms