C++ embraces the idea of undefined behavior.
Not all C++ operations have behavior defined by the standard. This permits compilers to assume they never happen, and can result in much faster code in many cases.
Here, by leaving the result of using a std::optional
that is unengaged undefined, it the cost of accessing data stored in a std::optional
is the same as the cost of accessing data not stored in a std::optional
. The only costs are the extra room required, and you as a programmer promising to keep track of if it is engaged or not.
Now compilers are free to insert checks there, and some do in debug builds.
Note that usually C++ std
library types include safe and unsafe methods for accessing data.
The fact that invalid pointers sometimes result in a sigsev is because most OS's protect addresses around 0 and crash programs that access it. This is because this was low cost, and it catches a bunch of bad behavior from many assembly, C and C++ programs.
If you want optional to throw when empty, use .value()
. If you don't, use operator*
. If you want a default value if one isn't there, use .value_or
.