When should I use std::optional in C++?

In what situations is it appropriate to use std::optional instead of just regular values or pointers?

You should consider using std::optional in C++ when you have a value that may or may not be present, such as:

Function return values

If a function might not always return a meaningful value, std::optional is a good way to represent that. For example:

#include <optional>
#include <string>

std::optional<std::string> GetMiddleName(
  const std::string& fullName) {
  // Parse full name
  // if middle name found, return it
  // else return empty optional
  return std::nullopt;
}

Class members

If a class has a field that is not always applicable or known at construction time, std::optional is a safe way to model that:

#include <optional>
#include <string>

class Character {
  std::string name;

  // age may not be known
  std::optional<int> age;
};

Optional function arguments

While default arguments are often used for this, std::optional can make it more explicit:

#include <optional>

void SetVolume(std::optional<double> volume) {
  if (volume) {
    // set volume to *volume
  } else {
    // set to default volume
  }
}

In general, std::optional is useful when you need to distinguish between a value not being present vs the value being present but potentially 0, empty string, null pointer etc. It makes your code's intent clearer.

Nullable Values, std::optional and Monadic Operations

A comprehensive guide to using std::optional to represent values that may or may not be present.

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

std::optional vs pointers in C++
When should I use std::optional instead of a pointer in C++? What are the differences?
Accessing the value in a std::optional
What is the best way to access the value stored in a std::optional? When should I use value() vs operator*?
Using std::optional for class members
How can I use std::optional for members in my C++ classes? Can you provide an example?
Checking if a std::optional has a value
What are the different ways to check if a std::optional contains a value?
Monadic operations with std::optional
Can you explain and provide examples of the monadic operations available for std::optional in C++23?
Using std::optional as a return type
When is it appropriate to use std::optional as a return type for a function?
Performance considerations with std::optional
Are there any performance considerations to keep in mind when using std::optional?
Using std::optional with pointers
Can std::optional be used with pointers? If so, how?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant