比特菲尔德(Bitfield)是否将整个类型的整个INT视为常见的初始序列?
我想知道以下内容是否有效C ++:
union id {
struct {
std::uint32_t generation : 8;
std::uint32_t index : 24;
};
std::uint32_t value;
};
我想要这个,以便我可以单独访问 generation
index ,这可以使整个数字访问。既然它们都是 std :: uint32_t
,那么这不应该是ub吗?
我计划这样使用它:
auto my_id = id{
.generation = 1,
.index = 4,
};
auto my_id_value = std::uint32_t{id.value};
如果是UB,是否有另一种方法可以使这项工作并根据C ++标准有效?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
通过
该措辞仍然可以在在当前的草稿中,包括一个示例清楚地说明与非静态数据成员相同类型的比特场将不是常见初始序列的一部分。
因此, [class.mem.general] 25 << /a>允许在联合标准类中的常见初始序列中访问非活动成员,在您的情况下不适用于
id.value
auto> auto my_id_value = std: :uint32_t {id.value};
具有未定义的行为。By resolution of CWG 645 (for C++11; not sure whether it is supposed to apply to C++98 as DR) the common initial sequence requires corresponding non-static data members or bit-fields in the two classes (by declaration order) to either be both bit-fields (of the same width) or neither be bit-fields.
The wording for that can still be found in [class.mem.general]/23 in the current draft, including an example stating clearly that a bit-field of the same type as a non-static data member will not be part of the common initial sequence.
Therefore the exceptional rule in [class.mem.general]25 allowing access to inactive members in the common initial sequence of standard-layout class members in a union doesn't apply in your case and reading
id.value
inauto my_id_value = std::uint32_t{id.value};
has undefined behavior.