Why does std::optional operator* not have debug mode assertion for has_value()?

I perfectly understand that because of performance reasons the operator* in std::optional does not make any checks for the actual existence of a contained value. However, in debug mode performance considerations should not matter and it would make a lot of sense to me that some kind of assertion should be made while in debug mode.

Visual studio doesn't seem to have such an assertion (though I am not sure of other compilers).

My question is: Is there any fundamental reason why the compiler would NOT make such an assertion on debug mode or is it just a missing feature?

1 answer

  • answered 2019-04-17 12:24 lubgr

    Is there any fundamental reason why the compiler would NOT make such an assertion on debug mode or is it just a missing feature?

    ODR violations. std::optional is a class template and hence implemented in a header. Different behavior of code inside a header for different preprocessor symbols is as dangerous as it gets. Consider this example (not tested, you'll get the point):

    clang++ -DNDEBUG usesOptionalOfInt.cpp -shared -c -o myLib.so
    clang++ alsoUsesOptionalOfInt.cpp main.cpp -lmyLib -o ./ub-please
    

    There you go with undefined behavior. Note that it's very unlikely that the difference in std::optional::operator* would actually cause any harm in this example, but still - you want to avoid these situations.