Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

trivially default constructible std::optional and std::variant

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.

like image 354
Tomilov Anatoliy Avatar asked Dec 03 '15 08:12

Tomilov Anatoliy


People also ask

Is trivially default constructible?

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.

What is STD variant in C++?

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).

Is default constructible C++?

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.

Where can I use std variant?

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 .


2 Answers

Your answer is correct: you cannot. The specification requires that its "initialized flag" is set to false upon default construction.

like image 69
Andrzej Avatar answered Oct 29 '22 21:10

Andrzej


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.

like image 36
MikeMB Avatar answered Oct 29 '22 21:10

MikeMB