Nullable Values using std::optional

std::optional vs pointers in C++

When should I use std::optional instead of a pointer in C++? What are the differences?

Illustration representing computer hardware

std::optional and pointers in C++ serve similar purposes - they both allow you to express that a value may or may not be present. However, there are some key differences:

  1. Clarity of intent: A pointer could be null for a variety of reasons - optional argument, not yet initialized, error condition, etc. An std::optional makes it explicit that the absence of a value is a valid state.
  2. No null dereferences: Dereferencing a null pointer leads to undefined behavior. std::optional provides safe ways to check for and access the contained value.
  3. Value semantics: std::optional provides value semantics, which means it behaves like a regular value type. Pointers have reference semantics.
  4. Allocation: std::optional directly contains the object, so no separate allocation is required. Pointers, especially std::unique_ptr and std::shared_ptr, typically allocate the object on the heap.

Here's an example illustrating the difference:

#include <optional>

class Character {
  // Character may or may not have health
  std::optional<int> health;

  // Character has a score, which may be
  // pointed to by other objects
  int* score;
};

In general, prefer std::optional when you need to express that a value may not be present. Use pointers when you need reference semantics, shared ownership (std::shared_ptr), or polymorphism.

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:

  • 125 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