What is the difference between std::optional and returning a null pointer?

Last updated 21 June 2026

  • std::optional<T> is a value-semantic wrapper that stores any type inline (no heap allocation) and states only "a value may be absent". A null pointer also implies indirection and raises ownership/dangling questions.

  • Access is safer: has_value() checks presence, value_or() gives a default, and value() throws std::bad_optional_access instead of crashing on a null dereference.

  • Use a pointer (or std::optional<std::reference_wrapper<T>>) to refer to an existing object, and a smart pointer for polymorphism.

  • https://github.com/Devinterview-io/cpp-interview-questions
All C++ interview questions