https://gcc.gnu.org/bugzilla/show_bug.cgi?id=102712

            Bug ID: 102712
           Summary: std::optional::operator* should assert on unset value
           Product: gcc
           Version: unknown
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: libstdc++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: ott at fb dot com
  Target Milestone: ---

It is UB to call operator* on an unset std::optional, and when doing so it is
easy to hit time-traveling UB, resulting in behavior that is very hard to
debug. 

For example, setting a field of an unset optional with operator-> may look like
it succeeded, and the rest of the program will behave as if the optional was
set, but it will silently leak memory because the destructor won't run. Another
plausible scenario is having an optional<X> where X has an operator bool(), and
spelling "if (*opt)" when the intention is to spell "if (opt)". The program
compiles and the optional is just assumed set around the condition.

Even UBSan with some of the strictest settings doesn't detect this.

All major implementations of the type have defined behavior in debug builds:

- libc++ asserts
https://github.com/llvm-mirror/libcxx/blob/master/include/optional#L905

- boost asserts
https://github.com/boostorg/optional/blob/develop/include/boost/optional/optional.hpp#L1213

- abseil asserts
https://github.com/abseil/abseil-cpp/blob/master/absl/types/optional.h#L428

- folly throws (in any compilation mode)
https://github.com/facebook/folly/blob/master/folly/Optional.h#L330
https://github.com/facebook/folly/blob/master/folly/Optional.h#L297

So anyone migrating from any of these is in for a world of hurt. 
Please consider adding an assertion in libstdc++.

Reply via email to