This was previously done implicitly in boost::optional by BOOST_ASSERT.
Also, it was checked at runtime by valgrind if for some reason the
assert was disabled.
std::optional dereference won't assert, so add the Assert here
explicitly.
The explicit Assert also helps to document the code better.
This is a partial backport of core#20671 and a follow-up to D8494