While reading through GCC's implementation of std::optional
I noticed something interesting. I know boost::optional
is implemented as follows:
template <typename T>
class optional {
// ...
private:
bool has_value_;
aligned_storage<T, /* ... */> storage_;
}
But then both libstdc++ and libc++ (and Abseil) implement their optional
types like this:
template <typename T>
class optional {
// ...
private:
struct empty_byte {};
union {
empty_byte empty_;
T value_;
};
bool has_value_;
}
They look to me as they are functionally identical, but are there any advantages of using one over the other? (Except for the obvious lack of placement new in the latter which is really nice.)