是否可以在c ++中创建一个占用少于一个字节内存的类型? [英] Is it possible to create a type in c++ that takes less than one byte of memory?

查看:66
本文介绍了是否可以在c ++中创建一个占用少于一个字节内存的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我的计算,我只需要使用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 C ++内存模型一章中说(重点是):

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 ++中创建一个占用少于一个字节内存的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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