C++ 语言标准中定义了 sizeof(bool) 吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4897844/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 16:52:44  来源:igfitidea点击:

Is sizeof(bool) defined in the C++ language standard?

c++booleansizeofimplementation-defined-behavior

提问by 0xbadf00d

I can't find an answer in the standard documentation. Does the C++ language standard require sizeof(bool)to always be 1 (for 1 byte), or is this size implementation-defined?

我在标准文档中找不到答案。C++ 语言标准是否要求sizeof(bool)始终为 1(对于 1 个字节),或者此大小是否由实现定义?

回答by GManNickG

sizeof(bool)is implementation defined, and the standard puts notable emphasis on this fact.

sizeof(bool)是实现定义的,标准非常强调这一事实。

§5.3.3/1, abridged:

§5.3.3/1,节略:

sizeof(char), sizeof(signed char)and sizeof(unsigned char)are 1; the result of sizeofapplied to any other fundamental type is implementation-defined. [Note: in particular, sizeof(bool)and sizeof(wchar_t)are implementation-defined.69)]

sizeof(char)sizeof(signed char)sizeof(unsigned char)为 1;的结果sizeof应用于任何其它类型的基本是实现定义。[注意:特别是,sizeof(bool)并且sizeof(wchar_t)是实现定义的。69)]

Footnote 69):

脚注 69):

sizeof(bool)is not required to be 1.

sizeof(bool)不需要为 1。

回答by Yi Ling

http://msdn.microsoft.com/en-us/library/tf4dy80a.aspx

http://msdn.microsoft.com/en-us/library/tf4dy80a.aspx

"In Visual C++4.2, the Standard C++ header files contained a typedef that equated bool with int. In Visual C++ 5.0 and later, bool is implemented as a built-in type with a size of 1 byte. That means that for Visual C++ 4.2, a call of sizeof(bool) yields 4, while in Visual C++ 5.0 and later, the same call yields 1. This can cause memory corruption problems if you have defined structure members of type bool in Visual C++ 4.2 and are mixing object files (OBJ) and/or DLLs built with the 4.2 and 5.0 or later compilers."

“在 Visual C++4.2 中,标准 C++ 头文件包含一个 typedef,将 bool 与 int 等同。在 Visual C++ 5.0 及更高版本中,bool 被实现为大小为 1 个字节的内置类型。这意味着对于 Visual在 C++ 4.2 中,调用 sizeof(bool) 产生 4,而在 Visual C++ 5.0 和更高版本中,相同的调用产生 1。如果您在 Visual C++ 4.2 中定义了类型为 bool 的结构成员并且正在混合对象,这可能会导致内存损坏问题使用 4.2 和 5.0 或更高版本编译器构建的文件 (OBJ) 和/或 DLL。”

回答by peoro

It's implementation defined. Only sizeof(char)is 1by the standard.

它是实现定义的。仅sizeof(char)1由标准。

回答by B?ови?

See 5.3.3 paragraph 1 :

见 5.3.3 第 1 段:

[Note: in particular, sizeof(bool) and sizeof(wchar_t) are implementation-defined.69) ]

[注意:特别是 sizeof(bool) 和 sizeof(wchar_t) 是实现定义的。69)]