1. Home
  2. Computer Science MCQs
  3. C++ and Object-Oriented Programming
  4. What happens when std::optional::value() is called on a…

Added 30 Nov -0001

What happens when std::optional::value() is called on a disengaged optional?

  1. It returns a default-constructed value through the monadic transform path
  2. It throws std::bad_optional_access, unlike operator* which is unchecked Correct answer
  3. It returns a value-initialised object, zero in this case, with no diagnostic
  4. It is undefined behaviour, because optional performs no check at all

Correct answer

B. It throws std::bad_optional_access, unlike operator* which is unchecked

21 views

MCQSEXAM

Explanation

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.

Reference

Asked in: NTS, PPSC IT, Campus Interviews

Preparing for an exam?

Doubts & discussion

Not sure why the answer is B? Ask here and get an explanation.

Ask a doubt about this MCQ

Shown after review. No links please.

More C++ and Object-Oriented Programming MCQs

Practise all C++ and Object-Oriented Programming MCQs

Similar MCQs