比特菲尔德(Bitfield)是否将整个类型的整个INT视为常见的初始序列?

发布于 2025-02-09 09:06:38 字数 481 浏览 3 评论 0 原文

我想知道以下内容是否有效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 ++标准有效?

I was wondering if the following was valid C++:

union id {
    struct {
        std::uint32_t generation : 8;
        std::uint32_t index : 24;
    };
    std::uint32_t value;
};

I want this so I can access both generation and index separately, which keeping access to the whole number. Since they all are std::uint32_t, this shouldn't be UB right?

I plan to use it like that:

auto my_id = id{
    .generation = 1,
    .index = 4,
};

auto my_id_value = std::uint32_t{id.value};

If it is UB, is there another way to make this work and valid according to the C++ standard?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不弃不离 2025-02-16 09:06:38

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 in auto my_id_value = std::uint32_t{id.value}; has undefined behavior.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文