Nullable Values using std::optional

Using std::optional with pointers

Can std::optional be used with pointers? If so, how?

Illustration representing computer hardware

Yes, std::optional can be used with pointers. This is particularly useful when you want to express that a pointer might be null, without the risk of null pointer dereferences.

Here's an example of how you might use std::optional with a pointer:

#include <iostream>
#include <optional>

class Player {
 public:
  Player(const std::string& name) : name(name) {}
  std::string name;
};

int main() {
  std::optional<Player*> player;

  // Player does not exist yet, player is nullopt
  if (!player) {
    std::cout << "Player does not exist\n";
  }

  // Create an object and assign it to player
  Player real_player("Hero");
  player = &real_player;

  // Player exists, we can access it
  if (player) {
    std::cout << "Player name: "
      << (*player)->name << '\n';
  }

  // Reset player to nullopt
  player = std::nullopt;

  // Player does not exist anymore
  if (!player) {
    std::cout << "Player does not exist\n";
  }
}

This will output:

Player does not exist
Player name: Hero
Player does not exist

When using std::optional with pointers, you need to be careful about the lifetime of the pointed-to object. In the example above, real_player must outlive player, otherwise player will be left pointing to an object that no longer exists.

Also, when accessing the pointer in an std::optional, you need to first dereference the optional (using *) and then dereference the pointer (using -> or *).

Using std::optional with pointers can help make your code more expressive and safer by explicitly representing the possibility of a null pointer.

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