The following code:
std::optional<std::string> so;
std::cout << so->size() << std::endl;
std::cout << so.has_value();
outputs:
0
0
My question is whether its safe to call : so->size()
on an empty optional. I used clang sanitizer, but it didnt report any UB in above code.
std::string* so=nullptr; so->size();
would be undefined. – Bethlehemstd::optional
because the dereferenced storage is internal tostd::optional
. For the pointer example, it is easy to statically determine the pointer isnullptr
. This is one of the first thing a static code analyzer would be programmed to detect. Forstd::optional
it is harder to determine if the internal storage contains an initialized object or not, unless you know how the internals ofstd::optional
work. A pointer to that storage will always be a valid pointer to something. It's hard to know if that something is aT
or just storage. – Calabresi