Trivially standard constructive std :: optional and std :: variant

Is it possible to enable the std::optional construct (currently std::experimental::optional ) in such a way that for the standard default constructive type T corresponding std::optional< T > also trivial by default constructive?

The same question returning std::variant and its integral discriminator.

My own answer: "No, it cannot be constructed in this way, because the value of its integral discriminator obtained by initialization by default will be undefined if the object has an automatic storage duration or if it reinterpret_cast -ed from non- -zero-initialized storage. " The requirement for the user to initialize the value each time is not allowed in my opinion.

+5
source share
2 answers

Your answer is correct: you cannot. The specification requires that its “initialized flag” be set to false by default.

+8
source

As you explained, you cannot implement std :: optional this way because you change its semantics (is_trivially_default_constructible is part of the class interface).

However, if you need this semantics for some reason in your code, there is no reason why you could not implement a very similar optional class, which is by default constructive by default. Then, when used, just zero initializes it with {} and - if that is what you want - treat zero as true in the bool statement.

+3
source

Source: https://habr.com/ru/post/1237310/


All Articles