What happens when std::optional::value() is called on a disengaged optional?
Correct answer
B. It throws std::bad_optional_access, unlike operator* which is unchecked
21 views
B. It throws std::bad_optional_access, unlike operator* which is unchecked
21 views
std::optional::value() checks the engaged flag and throws std::bad_optional_access when the optional is empty, whereas operator* and operator-> are unchecked and give undefined behaviour. value_or(default) is the non-throwing alternative that supplies a fallback. Unlike a pointer, an optional never holds a null value, so emptiness is tracked separately from any contained object.
Asked in: NTS, PPSC IT, Campus Interviews
Not sure why the answer is B? Ask here and get an explanation.