Namespaces
Variants
Views
Actions

std::optional<T>::operator->, std::optional<T>::operator*

From cppreference.com
< cpp‎ | utility‎ | optional
 
 
Utilities library
General utilities
Date and time
Function objects
Formatting library (C++20)
(C++11)
Relational operators (deprecated in C++20)
Integer comparison functions
(C++20)
Swap and type operations
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
Common vocabulary types
(C++11)
(C++17)
(C++17)
(C++17)
(C++17)

Elementary string conversions
(C++17)
(C++17)
 
 
constexpr const T* operator->() const;
(1) (since C++17)
constexpr T* operator->();
(1) (since C++17)
constexpr const T& operator*() const&;
(2) (since C++17)
constexpr T& operator*() &;
(2) (since C++17)
constexpr const T&& operator*() const&&;
(2) (since C++17)
constexpr T&& operator*() &&;
(2) (since C++17)

Accesses the contained value.

1) Returns a pointer to the contained value.
2) Returns a reference to the contained value.

The behavior is undefined if *this does not contain a value.

Contents

[edit] Parameters

(none)

[edit] Return value

Pointer or reference to the contained value.

[edit] Exceptions

(none)

[edit] Notes

This operator does not check whether the optional contains a value! You can do so manually by using has_value() or simply operator bool(). Alternatively, if checked access is needed, value() or value_or() may be used.

[edit] Example

#include <optional>
#include <iostream>
#include <string>
 
int main()
{
    using namespace std::string_literals;
 
    std::optional<int> opt1 = 1;
    std::cout<< "opt1: "  << *opt1 << '\n';
 
    *opt1 = 2;
    std::cout<< "opt1: "  << *opt1 << '\n';
 
    std::optional<std::string> opt2 = "abc"s;
    std::cout<< "opt2: " << *opt2 << " size: " << opt2->size() << '\n';
 
    // You can "take" the contained value by calling operator* on a rvalue to optional
 
    auto taken = *std::move(opt2);
    std::cout << "taken: " << taken << " opt2: " << *opt2 << "size: " << opt2->size()  << '\n';
}

Output:

opt1: 1
opt1: 2
opt2: abc size: 3
taken: abc opt2: size: 0

[edit] See also

returns the contained value
(public member function) [edit]
returns the contained value if available, another value otherwise
(public member function) [edit]