When should std::optional model absence instead of a pointer or sentinel, and what access and lifetime pitfalls remain?
Show answer and explanation
std::optional owns either one nested T value or no value, making absence explicit without assigning a magic sentinel. It fits optional value semantics; a pointer is still appropriate when identity, polymorphism, non-owning observation, or separately allocated ownership is the real model. Check engagement before operator* or operator->; value() instead throws bad_optional_access when empty. Resetting, reassigning, moving, or destroying the optional can invalidate references to its contained object, and standard C++20 optional does not hold reference types.
std::optional owns either one nested T value or no value, making absence explicit without assigning a magic sentinel. It fits optional value semantics; a pointer is still appropriate when identity, polymorphism, non-owning observation, or separately allocated ownership is the real model. Check engagement before operator* or operator->; value() instead throws bad_optional_access when empty. Resetting, reassigning, moving, or destroying the optional can invalidate references to its contained object, and standard C++20 optional does not hold reference types.
Connect the conclusion directly to the type, lifetime, ownership, overload-resolution rule, or library contract present in the question. State implementation dependence or a violated precondition explicitly instead of merely guessing output.