2 ms·
yes *optional and optional-> are UB if the optional is none. But in your code that's perfectly well defined because you guarded it with that if that made sure i
by kllrnohj 4y ago
yes *optional and optional-> are UB if the optional is none. But in your code that's perfectly well defined because you guarded it with that if that made sure it wasn't none in the first place.
The reason they are UB is because the comments that it's similar to a null pointer are incorrect. std::optional doesn't store a pointer. It stores a value, and it's required that the value isn't constructed for a none optional. That way you don't have to have an empty no-args constructor nor ensure the constructor is side-effect free. And because the WG doesn't control your code, nor does the compiler, the resulting behavior can't be well defined other than by having operator-> have an extra if check & throw. Which if that's the behavior you want, that's what optional's value() gives you.