C ++中的多个相邻位字段

问题描述 投票:1回答:3

我在浏览cppreference时看到了多个相邻的位域。

unsigned char b1 : 3, : 2, b2 : 6, b3 : 2;

所以,

  • 它的目的是什么?
  • 我应该何时何地使用它?
c++ structure bit-fields
3个回答
1
投票

显然,使用按位运算消耗更少的内存。例如,这对嵌入式编程可能很重要。

你也可以使用std::vector<bool>,它可以(通常也有)bitfield实现。


0
投票
Multiple adjacent bit fields are usually packed together (although this behavior is implementation-defined)

如果希望编译器在多位字段分配期间不添加填充或执行结构对齐,则可以在单个变量中编译它们。

struct x
{
  unsigned char b1 : 4;  // compiler will add padding after this. adding to the structure size.
  unsigned char b2 : 3; // compiler will add padding here too!  sizeof(x) is 2.
}


struct y
{
    unsigned char b1 : 4, : 3;   // padding will be added only once.  sizeof(y) is 1
}

或者,如果要在单个变量中分配更大的位字段

struct x
{
    unsigned char b1 :9;   //warning: width of 'x::b1' exceeds its type
};


struct y
{
    unsigned char b1 :6, :3;   //no warning
};

0
投票

c++draft说:

3内存位置是标量类型的对象或相邻位域的最大序列都具有非零宽度。[注意:语言的各种功能,如引用和虚函数,可能涉及无法访问的附加内存位置程序,但由实现管理.-结束注释]两个或多个执行线程([intro.multithread])可以访问单独的内存位置而不会相互干扰。

© www.soinside.com 2019 - 2024. All rights reserved.