One-byte bool. Why?(一字节布尔值.为什么?)
问题描述
在 C++ 中,为什么 bool 需要一个字节来存储真或假,而只有一位就足够了,比如 0 代表假,1 代表真?(为什么Java也需要一个字节?)
In C++, why does a bool require one byte to store true or false where just one bit is enough for that, like 0 for false and 1 for true? (Why does Java also require one byte?)
其次,使用下面的安全性如何?
Secondly, how much safer is it to use the following?
struct Bool {
bool trueOrFalse : 1;
};
第三,即使是安全的,上面的野外技术真的有用吗?因为我听说我们在那里节省了空间,但编译器生成的访问它们的代码仍然比生成的访问原语的代码更大更慢.
Thirdly, even if it is safe, is the above field technique really going to help? Since I have heard that we save space there, but still compiler generated code to access them is bigger and slower than the code generated to access the primitives.
推荐答案
为什么 bool 需要一个字节来存储 true 或 false 而只有一位就足够了
Why does a bool require one byte to store true or false where just one bit is enough
因为 C++ 中的每个对象都必须是可单独寻址的*(也就是说,您必须能够拥有指向它的指针).您无法解决单个位(至少不能在传统硬件上).
Because every object in C++ must be individually addressable* (that is, you must be able to have a pointer to it). You cannot address an individual bit (at least not on conventional hardware).
使用以下的安全性如何?
How much safer is it to use the following?
它是安全的",但效果并不大.
It's "safe", but it doesn't achieve much.
上述现场技术真的有用吗?
is the above field technique really going to help?
不,出于与上述相同的原因;)
No, for the same reasons as above ;)
但编译器生成的访问它们的代码仍然比生成的访问原语的代码更大且更慢.
but still compiler generated code to access them is bigger and slower than the code generated to access the primitives.
是的,这是真的.在大多数平台上,这需要访问包含字节(或 int
或其他),然后执行位移和位掩码操作以访问相关位.
Yes, this is true. On most platforms, this requires accessing the containing byte (or int
or whatever), and then performing bit-shifts and bit-mask operations to access the relevant bit.
如果您真的关心内存使用情况,可以使用 std::bitset
在 C++ 或 BitSet
在 Java 中,用于打包位.
If you're really concerned about memory usage, you can use a std::bitset
in C++ or a BitSet
in Java, which pack bits.
* 有少数例外.
这篇关于一字节布尔值.为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:一字节布尔值.为什么?


- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01