top | item 40263996

(no title)

lorenzhs | 1 year ago

There is no implicit conversion (except to bool, but that tells you whether the optional contains a value), and operator* / operator-> throw std::bad_optional_access if it’s empty. See https://en.cppreference.com/w/cpp/utility/optional

discuss

order

tialaramex|1 year ago

You're describing what it would do in a sane world where WG21 cared about safety.

In this world, as the document you've linked says: "The behavior is undefined if *this does not contain a value."

The operators for such access are actually `noexcept` - the exception you're apparently relying on would be illegal.

lorenzhs|1 year ago

Should’ve checked my own link instead of relying on memory — I might have some code to revisit on Monday. That’s insane, thanks for correcting me!

kzrdude|1 year ago

Can we salvage this by forbidding * on optional with compiler warnings (as errors)?

masklinn|1 year ago

> and operator* / operator-> throw std::bad_optional_access if it’s empty.

Of course not, they’re literally `noexcept`, what they do is UB if empty.

value() will throw.

formerly_proven|1 year ago

Step 1 of API design: Always make the easiest and shortest way the wrong way.