5

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?

Stack Danny
  • 7,754
  • 2
  • 26
  • 55

1 Answers1

6

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.

lubgr
  • 37,368
  • 3
  • 66
  • 117
  • 1
    But if one is to use STL over static libraries, you have to have them built with the same compiler options, anyway, otherwise nothing will work! std::vector is full of assertions in Visual Studio already (see _STL_VERIFY() under various _ITERATOR_DEBUG_LEVELs ). What is the difference between those assertions and the one that @FranciscoMartinez proposes ? – Grim Fandango Jun 01 '21 at 09:42
  • Those are reserved names - client code is not allowed to mess with those. From [cppreference](https://en.cppreference.com/w/cpp/language/identifiers): "the identifiers that begin with an underscore followed by an uppercase letter are reserved". This is the main difference to e.g. the `NDEBUG` macro. – lubgr Jun 01 '21 at 12:09