c++ - 是否可以在 C++ 中创建一个占用少于一个字节内存的类型?

标签 c++ types byte primitive-types

对于我的计算,我只需要使用 7 位空间,所以我使用的是 char 类型。但是我想知道是否可以声明我自己的使用少于一个字节内存的类型?

最佳答案

不是真的。在结构内部,您可以使用 bit fields .因此,如果您知道您将需要一定数量的条目,这将是一种节省一些位的方法(但请注意,该结构将始终至少填充到下一个字节总数)。另请注意,由于“普通”CPU 无法处理小于八位位组/字节的数量,因此对这些位字段值的访问可能会更慢,因为编译器必须生成额外的指令来获取/存储值“在中间”。因此,为了节省一些位,您必须花费一些 CPU 时间。

C++11 standard1.7 The C++ 内存模型(强调我的)一章中说:

The fundamental storage unit in the C++ memory model is the byte. A byte is at least large enough to contain any member of the basic execution character set (2.3) and the eight-bit code units of the Unicode UTF-8 encoding form and is composed of a contiguous sequence of bits, the number of which is implementation- defined.

换句话说:C++ 中最小的可寻址单元至少有 8 位宽。

旁注:如果您想知道:there are machines like DSPs that can only address units larger than 8 bits at a time ;对于这样的机器,编译器可以将“字节”定义为例如 16 位宽。

关于c++ - 是否可以在 C++ 中创建一个占用少于一个字节内存的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29684487/

相关文章:

c++ - 单链表段错误问题

c++ - 测试项目中Makefile中的Qtcreator错误

指针成员的 c++/CLI 包装器 - c++ 单例实例

c++ 使用子类 'type cast' 错误

c# - 如何在 c#.net 中将结构转换为字节数组,但结构大小仅在运行时定义

c++ - 用 0x 作为十六进制值的前缀

C#、.net、通用编程架构。 GetType 或枚举 : Which is better?

c++ - 什么是 C++ 中的未命名类型?

java - Java 中具有非十六进制字符的等效 Perl 包 ("H*")

python - 翻转一个字节的最后一位