Nullable Values using std::optional

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?

Illustration representing computer hardware

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.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved