|
|
|
|
|
by account4mypc
1887 days ago
|
|
boost::optional was designed to mimic pointers. Before boost::optional, some programmers would return a T* as a caveman's optional<T>. Boost wanted to preserve the syntax of *, ->, and operator bool. Dereferencing a null ptr is UB, so operator* for optional was the same. I agree it would be nice if you could get an assert in operator*. But you can already fire up a debugger or sanitize build and get a nice error message anyway, so it's nbd. |
|
If, as you wrote, operator* for an optional that doesn’t contain a value is UB, it can do whatever it wants, including assert.
I think the problem is that there’s an implicit requirement that operator* optionals that do contain a value is as fast as a pointer dereference.
(Aside: reading https://en.cppreference.com/w/cpp/utility/optional, I wonder how one can misuse “When an object of type optional<T> is contextually converted to bool, the conversion returns true if the object contains a value and false if it does not contain a value.” to write obfuscated code or hide back doors using optional<bool>)