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

徘徊边缘 提交于 2019-12-01 17:24:29

问题


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.


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/34061095/trivially-default-constructible-stdoptional-and-stdvariant

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!