问题描述
对于我的计算,我只需要使用 7 位空间,所以我使用的是 char 类型.但是我想知道是否可以声明我自己的使用少于一字节内存的类型?
For my computation I only need to use 7-bit space so I am using a char type. However I wonder if it is possible to declare my own type that uses less than one byte of memory?
推荐答案
并非如此.在结构体中,您可以使用位字段.因此,如果您知道您需要一定数量的固定条目,这将是一种节省一些位的方法(但请注意,该结构将始终至少填充到下一个完整的字节数).另请注意,由于普通"CPU 无法处理小于八位字节/字节的数量,因此对这些位字段值的访问可能会更慢,因为编译器必须生成额外的指令来获取/存储值在中间".所以为了节省几位,你必须花费一些CPU时间.
Not really. Inside a struct, you can make use of bit fields. So if you know you'll need a certain, fixed amount of entries, this would be a way to save a few bits (but note that the struct will always be padded to at least the next whole amount of bytes). Also note that due to the fact that "normal" CPUs can't address amounts smaller than an octet/byte, the access to these bit field values might be slower because of the extra instructions the compiler has to generate to get/store a value "in the middle". So in order to save a few bits, you have to spend some CPU time.
C++11 标准 在 1.7 The C++ memory model 一章中说(重点是我的):
The C++11 standard says in chapter 1.7 The C++ memory model (emphasis mine):
C++ 内存模型中的基本存储单元是字节.一个字节至少大到足以包含基本执行字符集 (2.3) 的任何成员和 Unicode UTF-8 编码形式的八位代码单元和由连续的位序列组成,其数量由实现定义.
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 位宽.
In other words: the smallest addressable unit in C++ is at least 8 bits wide.
旁注:如果您想知道:有些机器,比如 DSP,一次只能寻址大于 8 位的单元;对于这样的机器,编译器可以将字节"定义为例如 16 位宽.
Side-note: In case you're wondering: there are machines like DSPs that can only address units larger than 8 bits at a time; for such a machine, the compiler may define "byte" to be, for example, 16 bits wide.
这篇关于是否可以在 C++ 中创建一种占用少于一个字节内存的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!