c++undefined-behaviorstdoptional

Is use of empty std::optional<string> UB or not?


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.


Solution

  • Using operator-> on an empty std::optional is Undefined Behavior, regardless of what type T is in std::optional<T>.

    According to cppreference on std::optional<T>::operator-> :

    The behavior is undefined if *this does not contain a value.