普通默认构造 std::optional 和 std::variant
trivially default constructible std::optional and std::variant
是否允许以这种方式设计std::optional
(目前std::experimental::optional
),对于平凡的默认可构造类型T
对应的std::optional< T >
也是平凡的默认可构造的?
同样的问题重新计算 std::variant
及其积分判别器。
我自己的回答是:"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."我认为不允许用户每次都进行值初始化。
您的回答是正确的:不能。规范要求其"initialized flag"在默认构造时设置为false
。
正如您自己解释的那样,您不能以这种方式实现 std::optional,因为您会更改其语义(is_trivially_default_constructible 是 class 接口的一部分)。
但是,如果您出于某种原因在您的代码中需要这种语义,那么您没有理由不能实现一个非常相似的可选 class,它可以默认构造。然后,在使用时,只需通过 {} 将其初始化为零,并且 - 如果这是您想要的 - 在 bool 运算符中将零视为 true。
是否允许以这种方式设计std::optional
(目前std::experimental::optional
),对于平凡的默认可构造类型T
对应的std::optional< T >
也是平凡的默认可构造的?
同样的问题重新计算 std::variant
及其积分判别器。
我自己的回答是:"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."我认为不允许用户每次都进行值初始化。
您的回答是正确的:不能。规范要求其"initialized flag"在默认构造时设置为false
。
正如您自己解释的那样,您不能以这种方式实现 std::optional,因为您会更改其语义(is_trivially_default_constructible 是 class 接口的一部分)。
但是,如果您出于某种原因在您的代码中需要这种语义,那么您没有理由不能实现一个非常相似的可选 class,它可以默认构造。然后,在使用时,只需通过 {} 将其初始化为零,并且 - 如果这是您想要的 - 在 bool 运算符中将零视为 true。