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

1

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?

Pompey answered 17/4, 2019 at 12:18 Comment(1)
The more your debug build diverges from the release, the less useful it becomes.Edgebone
B
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.

Blayze answered 17/4, 2019 at 12:24 Comment(2)
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 ?Puissant
Those are reserved names - client code is not allowed to mess with those. From cppreference: "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.Blayze

© 2022 - 2025 — McMap. All rights reserved.