Nullable Values using std::optional

Using std::optional as a return type

When is it appropriate to use std::optional as a return type for a function?

Illustration representing computer hardware

Using std::optional as a return type is a good choice when a function might not always have a meaningful value to return. Some common scenarios include:

Functions that search for a value

If a function searches for a value in a data structure and the value might not be present, it can return an std::optional. The presence of a value in the returned optional indicates that the value was found.

#include <optional>
#include <vector>

std::optional<int> find_value(
  const std::vector<int>& vec, int value) {
  for (int i : vec) {
    if (i == value) {
      return i;
    }
  }
  return std::nullopt;
}

Functions that parse input

If a function tries to parse a value from input and the input might be invalid, it can return an std::optional. The presence of a value in the returned optional indicates that the parsing was successful.

#include <optional>
#include <string>

std::optional<int> parse_int(
  const std::string& s) {
  try {
    return std::stoi(s);
  } catch (...) {
    return std::nullopt;
  }
}

Functions that compute a result

If a function computes a result and the computation might fail or not be possible for certain inputs, it can return an std::optional. The presence of a value in the returned optional indicates that the computation succeeded.

#include <cmath>
#include <optional>

std::optional<double> sqrt_positive(double x) {
  if (x >= 0) {
    return sqrt(x);
  } else {
    return std::nullopt;
  }
}

In all these cases, using std::optional makes it clear to the caller that the function might not always return a value, and provides a clean way to handle that situation.

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