Is it permitable to design std::optional
(currently std::experimental::optional
) in such a way, that for trivially default constructible type T
corresponding std::optional< T >
is also trivially default constructible?
The same question regading std::variant
and its integral discriminator.
My own answer is: "No, it cannot be designed in this way, because value of its integral discriminator obtained during default initialization will be indeterminate if the object has automatic storage duration or if it is reinterpret_cast
-ed from non-zero-initialized storage." Requirement to the user to do value-initialization every time is not allowed on my mind.
A trivially default constructible type is a type which can be trivially constructed without arguments or initialization values, either cv-qualified or not. This includes scalar types, trivially default constructible classes and arrays of such types.
The class template std::variant represents a type-safe union. An instance of std::variant at any given time either holds a value of one of its alternative types, or in the case of error - no value (this state is hard to achieve, see valueless_by_exception).
A default constructible class is a class that has a default constructor (either its implicit constructor or a custom defined one). The is_default_constructible class inherits from integral_constant as being either true_type or false_type, depending on whether T is default constructible.
union s save memory because they allow a single piece of memory to be used for different types of objects at different times. Consequently, they can be used to save memory when we have several objects that are never used at the same time. std::variant uses the memory similar to the union .
Your answer is correct: you cannot. The specification requires that its "initialized flag" is set to false
upon default construction.
As you explained yourself, you can't implement std::optional in such a way, because you would change its semantics (is_trivially_default_constructible is part of the class interface).
However, if you require this semantic for some reason in your code, there is no reason, why you couldn't implement a very similar optional class that is trivially default constructible. Then, when used, just zero initialize it via {} and - if that is what you want - treat zero as true in the bool operator.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With