在c++中,

为什么布尔值是1字节而不是1位? 为什么没有4位或2位整数类型?

在为CPU编写模拟器时,我忽略了上述内容


当前回答

最简单的答案是;这是因为CPU以字节而不是位来寻址内存,按位的操作非常慢。

然而,在c++中可以使用位分配。对于位向量,有std::vector专门化,还有接受位大小条目的结构。

其他回答

因为在一般情况下,CPU以1字节作为基本单位分配内存,尽管一些CPU如MIPS使用4字节字。

但是vector以一种特殊的方式处理bool类型,vector<bool>为每个bool类型分配一个位。

因为CPU不能寻址任何小于字节的东西。

bool can be one byte -- the smallest addressable size of CPU, or can be bigger. It's not unusual to have bool to be the size of int for performance purposes. If for specific purposes (say hardware simulation) you need a type with N bits, you can find a library for that (e.g. GBL library has BitSet<N> class). If you are concerned with size of bool (you probably have a big container,) then you can pack bits yourself, or use std::vector<bool> that will do it for you (be careful with the latter, as it doesn't satisfy container requirments).

你可以有1位的bool型和4位和2位的int型。但这将导致一个奇怪的指令集,没有性能提升,因为这是一种不自然的方式来看待体系结构。“浪费”一个字节的大部分,而不是试图回收未使用的数据,实际上是有意义的。

根据我的经验,唯一一个把几个bool包进一个字节的应用程序是Sql Server。

考虑一下如何在模拟器级别实现这一点……

bool a[10] = {false};

bool &rbool = a[3];
bool *pbool = a + 3;

assert(pbool == &rbool);
rbool = true;
assert(*pbool);
*pbool = false;
assert(!rbool);