Why the sizeof(bool) is not defined to be one, by the Standard itself?(为什么标准本身没有将 sizeof(bool) 定义为 1?)
问题描述
char
、signed char
和 unsigned char
的大小由 C++ 标准本身定义为 1 个字节.我想知道为什么它也没有定义 sizeof(bool)
?
Size of char
, signed char
and unsigned char
is defined to be 1 byte, by the C++ Standard itself. I'm wondering why it didn't define the sizeof(bool)
also?
C++03 标准 $5.3.3/1 说,
C++03 Standard $5.3.3/1 says,
sizeof(char), sizeof(signed char) 和sizeof(unsigned char) 为 1;这sizeof 应用于任何其他的结果基本类型(3.9.1)是实现定义.[注:在特别是 sizeof(bool) 和sizeof(wchar_t) 是实现定义.69)
sizeof(char), sizeof(signed char) and sizeof(unsigned char) are 1; the result of sizeof applied to any other fundamental type (3.9.1) is implementation-defined. [Note: in particular,sizeof(bool) and sizeof(wchar_t) are implementation-defined.69)
我理解 sizeof(bool) 不能小于一个字节.但是有什么理由为什么它应该大于 1 个字节吗?我并不是说实现将它定义为大于 1,但标准让它由实现定义好像它可能大于 1.
I understand the rationale that sizeof(bool) cannot be less than one byte. But is there any rationale why it should be greater than 1 byte either? I'm not saying that implementations define it to be greater than 1, but the Standard left it to be defined by implementation as if it may be greater than 1.
如果没有理由 sizeof(bool)
大于 1,那么我不明白为什么标准没有将它定义为 1 字节
,因为它已经定义了 sizeof(char)
,而且都是变体.
If there is no reason sizeof(bool)
to be greater than 1, then I don't understand why the Standard didn't define it as just 1 byte
, as it has defined sizeof(char)
, and it's all variants.
推荐答案
许多平台无法有效加载小于 32 位的值.他们必须加载 32 位,并使用移位和掩码操作来提取 8 位.对于单个 bool
,你不希望这样,但对于字符串来说没问题.
Many platforms cannot effectively load values smaller than 32 bits. They have to load 32 bits, and use a shift-and-mask operation to extract 8 bits. You wouldn't want this for single bool
s, but it's OK for strings.
这篇关于为什么标准本身没有将 sizeof(bool) 定义为 1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么标准本身没有将 sizeof(bool) 定义为 1?
- C++ 协变模板 2021-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 静态初始化顺序失败 2022-01-01
- 从python回调到c++的选项 2022-11-16
- Stroustrup 的 Simple_window.h 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 近似搜索的工作原理 2021-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01