C ++:是否有可能在同一个字节内压缩`bool`对象?

问题描述 投票:10回答:2

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

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
2个回答
12
投票

你可以使用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;
}

0
投票

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

您可以看到this answer进行完整比较,但实际上由于结构化而有点字段会有一些开销,编译器可能会或可能不会实际将元素打包在一起以节省空间。

然而,比特集是专门为优化空间分配而设计的,并且还提供了一些专门用于比特翻转的有用功能。

bitset在逻辑上只是一个位数组,但是打包以节省空间。您可以像这样使用它:

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
© www.soinside.com 2019 - 2024. All rights reserved.