6

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.

Tomilov Anatoliy
  • 15,657
  • 10
  • 64
  • 169
  • Can I ask you in exchange why it is important to you? I can imagine why you would optional to be trivially-copyable. But why trivially-default-constructible? What does it buy you? – Andrzej Dec 03 '15 at 08:57
  • @Andrzej The container (like `optional` or `variant`) should be as generic as possible, isn't it? I attempt to design [`variant` for constexpr](http://codereview.stackexchange.com/questions/112218/trivial-full-fledged-variant-for-constexpr-proof-of-concept). And currently it has above ability. But I think "maybe I should to deny it?". – Tomilov Anatoliy Dec 03 '15 at 09:00
  • @Andrzej Eventually I found a "bug" in my `variant`. Default initialized objects has different behaviour in compile time (constexpr) and runtime. Then I read about [intiializations](http://en.cppreference.com/w/cpp/language/initialization). And found out, that there is UB to use my default intiialized `variant` on the stack. – Tomilov Anatoliy Dec 03 '15 at 09:02

2 Answers2

8

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

Andrzej
  • 5,027
  • 27
  • 36
4

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.

MikeMB
  • 20,029
  • 9
  • 57
  • 102