What is the difference between std::optional and returning a null pointer?
Last updated
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, andvalue()throwsstd::bad_optional_accessinstead 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.