布尔在内存中如何表示?

2022-01-19 00:00:00 types boolean c++

正如已经在 文档中讨论过的,一个 bool 数据类型至少占用一个字节的内存.之前在 SO 上提出了类似的问题(How a bool类型变量是否存储在内存中?(C++)),但是这个讨论和文档似乎只讨论布尔数据类型占用的空间量,而不是实际发生的情况在内存中当我这样做时:

As already discussed in the docs, a bool data type occupies at least a byte of memory. A similar question was asked on SO before (How a bool type variable is stored in memory? (C++)), but this discussion and the documentation only seem to discuss the amount of space occupied by a boolean data type, not what actually happens in memory when I do this:

bool b = true;

那么内存中到底发生了什么?未用于存储此信息的 7 位会发生什么?标准是否为此规定了行为?

So what does actually happen in memory? What happens to the 7 bits that are not used in storing this information? Does the standard prescribe behavior for this?

它们是未定义的吗?还是 C++ 总部的某个人这样做了:

Are they undefined? Or did someone at C++ headquarters just do this:

enum bool : char 
{
  false = 0,
  true = 1
};

推荐答案

标准规定 bool 值表现为整数类型,但没有指定它们在内存中的具体表示:

Standard states that bool values behave as integral types, yet it doesn't specify their concrete representation in memory:

"bool 类型的值为 truefalse.如下所述,bool值表现为整数类型.bool 类型的值参与整数提升" ~ C++03 3.9.1 §6

"Values of type bool are either true or false. As described below, bool values behave as integral types. Values of type bool participate in integral promotions" ~ C++03 3.9.1 §6

整数类型的同义词是整数类型.整数类型的表示应使用纯二进制计数系统定义值" ~ C++03 3.9.1 §7

然而它定义了从 boolint 的整体提升:

Yet it defines the integral promotion from bool to int:

"bool 类型的右值可以转换为 int 类型的右值,false 变为零和 true 合而为一.这些转换称为积分提升." ~ C++03 4.5 §4-5

"An rvalue of type bool can be converted to an rvalue of type int, with false becoming zero and true becoming one. These conversions are called integral promotions." ~ C++03 4.5 §4-5

以及从其他类型到bool的转换:

as well as conversion from other types to bool:

零值、空指针值或空成员指针值转换为false;任何其他值转换为true." ~ C++03 4.12 §1

"A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true." ~ C++03 4.12 §1

相关文章