gpt4 book ai didi

c++ - 位域如何与 C++ 中的位填充相互作用

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:29:40 25 4
gpt4 key购买 nike

见本题C版here .

当有填充位时,我有两个关于位域的问题。

假设我有一个结构定义为

struct T { 
unsigned int x: 1;
unsigned int y: 1;
};

Struct T 实际使用的只有两位。

问题 1:这两位是否始终是底层 unsigned int 的最低有效位?还是取决于平台?

问题2:那些未使用的30位是否总是初始化为0? C++ 标准对此有何规定?

最佳答案

Question 1: are these two bits always the least significant bits of the underlying unsigned int? Or it is platform dependent?

非常依赖于平台。该标准甚至有一条注释只是为了说明多少:

[class.bit]

1 ...Allocation of bit-fields within a class object is implementation-defined. Alignment of bit-fields is implementation-defined. Bit-fields are packed into some addressable allocation unit. [ Note: Bit-fields straddle allocation units on some machines and not on others. Bit-fields are assigned right-to-left on some machines, left-to-right on others.  — end note ]

您不能对位域的对象布局做太多假设。

Question 2: Are those unused 30 bits always initialized to 0? What does the C++ standard say about it?

您的示例有一个简单的聚合,因此我们可以枚举可能的初始化。没有指定初始化器...

T t;

... 将 default initialize它,使成员具有不确定的值(value)。另一方面,如果您指定空括号...

T t{};

...对象将是aggregate initialized ,因此位字段将使用 {} 本身进行初始化,并设置为零。但这仅适用于聚合的成员,即位域。没有指定填充位取什么值(如果有的话)。所以我们不能假设它们将被初始化为零。

关于c++ - 位域如何与 C++ 中的位填充相互作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56216675/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com