I know this ship has sailed due to ABI breakage it would require, but I wonder why originally implementations did not decide to use some magic bit pattern for std::string, std::vector, etc... to signal empty optional value. This obviously requires some "free" value in the bit representation of the type, so for example it would not work for int, size_t but many complex types have certain representations that can never occur for valid instance.
C++ could even specify some way to opt in for your type, e.g. by specializing
std::nullopt_sentinel
for user defined types.
My best guess is that complexity of specifying/implementing this(because you would need to implement sentinels for many many types in std::) was much greater than just using a bool always, but I wonder if there are other reasons.
Similar answer for Rust that seems to implement this sometimes
The standard library and any user specializing
std::optionalfor their own types are already free to implement it that way for types where it is possible (see [namespace.std] p2).Nothing in the specification of
std::optionalmandates use of aboolflag to indicate the presence of a value. How the empty state is identified is an implementation detail. The user ofstd::optionalcan't rely on observing anything else about the internal state if the optional is empty.