C++ std::optional vs Pointers: Representing "No Value" Safely

C++ std::optional vs Pointers: Representing "No Value" Safely

이 글의 핵심

Guide to std::optional vs pointers: when optional wins, when pointers are required, and performance notes.

When you need owning heap storage instead of optional, compare shared_ptr vs unique_ptr.

Introduction: “How should I represent null?”

C++ offers nullptr pointers and std::optional<T> (C++17) for “maybe no value,” with very different safety and cost profiles.

This article covers:

  • optional vs pointers
  • Type safety
  • Performance
  • Scenarios

1. Comparison

Aspectstd::optionalT*
StorageUsually inlineAddress-sized
Ownership modelOwns value stateAliases external object
Absent valuestd::nulloptnullptr
Safetyharder to “forget” checks (value()/bad_optional_access)easy to dereference nullptr

2. Type safety

optional encourages explicit checks: has_value(), value_or(), value() (throws if empty).


3. Performance

Microbenchmarks often show optional vs stack pointer checks in the same ballpark; heap pointers add allocation noise.


4. Scenarios

  • optional: optional<int> return from parsing; optional function parameters
  • pointers: virtual dispatch; pointing into existing storage
  • smart pointers: shared ownership (shared_ptr) when needed

Summary

SituationPrefer
Maybe-missing return by valueoptional
Polymorphic objectpointer/unique_ptr
Large object without copyingpointer/unique_ptr/out-param

  • shared_ptr vs unique_ptr
  • nullptr guide

Keywords

std::optional, optional vs pointer, C++17, null safety


  • variant vs union
  • any vs void*