CKTIS / C++
std::optional::operator-> — access a member of the contained value
Use `->` to access a member of the value stored in `std::optional`. In C++23, check that the optional contains a value before using the operator.
Version: ISO C++23; implementation support may vary
Syntax
In <optional>, std::optional<T> declares:
constexpr T* operator->() noexcept;
constexpr const T* operator->() const noexcept;
Member access: opt->member or opt->method(args...)
C++23 precondition: opt.has_value() is true when operator->() is called.std::optional::operator-> has been available in <optional> since C++17. In opt->member, C++ calls the overloaded operator, then applies built-in -> to the returned pointer. The operator returns T* for a non-const std::optional<T> and const T* for a const one. Both overloads are constexpr and noexcept; neither copies the value.
In C++23, calling this operator on an empty optional is undefined behavior: do not expect nullptr or an exception. Use if (opt) or opt.has_value() and access the value only while it is still present. The if (opt) test uses the explicit operator bool in a contextual conversion: it tests presence, not the value itself. For checked access, opt.value() throws std::bad_optional_access if no value is present.
*opt gives a reference instead of a pointer and also requires a value to be present. The pointer from operator-> is non-owning and does not extend the value's lifetime. Do not use it to access the value after its lifetime ends, for example after reset() or destruction of the optional.
In the example, fs is a namespace alias for std::filesystem. The & in const std::optional<fs::path>& borrowedpath declares an lvalue reference to a const-qualified type: the parameter does not copy the optional, and -> selects the const overload. An empty path is still a present value; path::empty() does not query the filesystem.
Examples
#include <filesystem>
#include <iostream>
#include <optional>
#include <utility>
namespace fs = std::filesystem;
void describe(const std::optional<fs::path>& borrowedpath)
{
if (borrowedpath) {
std::cout << (borrowedpath->empty() ? "empty path\n" : "nonempty path\n");
} else {
std::cout << "no value\n";
}
}
int main()
{
const std::optional<fs::path> present{std::in_place};
const std::optional<fs::path> absent;
describe(present);
describe(absent);
}
Result
empty path no value
The first call prints `empty path` because a value is present but the path is empty. The second prints `no value` and never evaluates `->`.
Related lessons
- C++ · Lesson 48 · Advanced · Version: 3