考虑一个具有多个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
都被压缩在同一个字节中?
发布于 2018-12-13 08:14:07
您可以使用bitfields。与副本一起工作。它是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;
}
发布于 2019-03-16 09:32:33
如果您真的关心节省空间,那么您可能应该使用bitset
而不是位字段。
您可以查看this answer进行完整的比较,但本质上,位字段由于是结构字段而会有一些开销,编译器可能会将元素打包在一起,也可能不会打包在一起,以节省空间。
然而,位集是专门为优化空间分配而制作的,并且还提供了一些专门用于位旋转的有用功能。
位集在逻辑上只是一个位数组,但为了节省空间而打包。你可以像这样使用它:
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
https://stackoverflow.com/questions/53753245
复制相似问题