一个字节的布尔。为什么? [英] One-byte bool. Why?

查看:187
本文介绍了一个字节的布尔。为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中,为什么一个布尔值需要一个字节来存储真或假,即只有一个位是足够的,像0假,1为真? (为什么Java也需要一个字节?)

其次,如何更安全的是它使用下面的?

 结构布尔{
    布尔trueOrFalse:1;
};

第三,即使是安全的,是上述领域的技术真的要帮忙吗?因为我听说,我们节省空间存在,但仍编译器生成code来访问它们比产生访问原语code更大和更慢。


解决方案

  

为什么一个布尔需要一个字节来存储真或假,即只有一个位是足够的。


由于在C ++中的每个对象必须是独立寻址 * (也就是说,你必须能够有一个指向它的指针)。不能解决的一个单独的位(至少不会在常规的硬件)。


  

如何更安全的是它使用下面的?


这是安全的,但它不实现多


  

在上述领域的技术真的要帮忙吗?


没有,出于同样的理由如上述)


  

但仍编译器生成code来访问它们比产生访问原语code更大和更慢。


是的,这是事实。在大多数平台上,这需要访问包含字节(或 INT 或其他),然后进行位变化和位掩码操作来访问的相关位。


如果你真的关心内存使用情况,您可以使用 和std :: bitset C ++或一个的 位集合 在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.

解决方案

Why does a bool require one byte to store true or false where just one bit is enough

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.

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.


If you're really concerned about memory usage, you can use a std::bitset in C++ or a BitSet in Java, which pack bits.


* With a few exceptions.

这篇关于一个字节的布尔。为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆