【问题标题】:C++: Is it possible to condense `bool` objects within the same byte?C++:是否可以在同一个字节内压缩“bool”对象?
【发布时间】:2018-12-13 00:06:54
【问题描述】:

考虑一个具有许多布尔属性的类

class A
{
  bool a;
  bool b;
  bool c;
  bool d;
  bool e;
  bool f;
};

虽然每个bool 对象可以用一个位表示,但这里每个属性都需要一个字节(如果我没记错的话)。该对象将占用 6 个字节,而不仅仅是 1 个字节(其中 6 位将被实际使用)。原因是位不可寻址,只有字节可寻址。

为了稍微压缩内存,可以使用vector<bool>bitset,然后通过它们的索引访问属性。例如,可以将 get 函数编写为

bool A::get_d() {data[3];}

理想情况下,我希望能够使用InstanceOfA.d 直接访问属性。是否可以这样做,同时确保我的所有 6 个bool 都被压缩在同一个字节内?

【问题讨论】:

    标签: c++ memory boolean byte bit


    【解决方案1】:

    您可以使用bitfields。适用于 Repl.it 的 gcc 版本 4.6.3。

    #include <iostream>
    
    struct Test 
    {
      bool a:1;
      bool b:1;
      bool c:1;
      bool d:1;
      bool e:1;
      bool f:1;
      bool g:1;
      bool h:1;
      //bool i:1; //would increase size to 2 bytes.
    };
    
    int main()
    {
      Test t;
      std::cout << sizeof(t) << std::endl;
      return 0;
    }
    

    【讨论】:

    • 正是我想要的!谢谢!我会尽可能接受答案。
    • 另一种选择是std::bitset
    • 但是请注意,这些字段的实际布局是实现定义的。语言定义不要求将它们打包。通常它们会,但如果它很重要,请检查它。
    【解决方案2】:

    如果您真的关心节省空间,您可能应该使用bitset 而不是位字段。

    您可以查看this answer 进行完整比较,但本质上,由于是结构,位字段会产生一些开销,并且编译器可能会或可能不会实际将元素打包在一起以节省空间。

    Bitsets 是专门为优化空间分配而设计的,并且还提供了一些专门用于位旋转的有用功能。

    位集在逻辑上只是一个位数组,但为了节省空间而打包。你可以这样使用它:

    std::bitset<8> bacon;
    bacon.set();    // 11111111
    bacon.reset(1); // 11111101 Note: counts index from the right
    
    std::bitset<4> fancy (std::string("1111"));
    fancy[1] = 0;      // 1101 Note: counts index from the right
    fancy.test(1) == 0 // true
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-06-24
      • 1970-01-01
      • 1970-01-01
      • 2020-05-30
      • 1970-01-01
      • 1970-01-01
      • 2012-04-03
      相关资源
      最近更新 更多