一字节布尔值.为什么?

2022-01-19 00:00:00 performance boolean c++ java primitive

在 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.

* 有少数例外.

相关文章