简体   繁体   English

我可以强制C ++类使用最少的空间进行编译吗?

[英]Can I force a C++ class to compile using the minimum amount of space?

I have a class that I will literally instantiate billions of. 我有一堂课,我将立即实例化数十亿个实例。 I did my best to put as little data as possible in it, and I got it down to 10 bytes when compiled for an x64 architecture: an unsigned short int and a size_t . 我尽力将尽可能少的数据放入其中,在针对x64体系结构进行编译时,我将其缩减为10个字节: unsigned short intsize_t When I mouse over sizeof(myclass) (in VS), however, it reports 16 bytes. 但是,当我将鼠标悬停在sizeof(myclass) (在VS中)上时,它将报告16个字节。 If I comment out either of the fields, the size of the class is what you'd expect, 10 bytes and 2 bytes respectively. 如果我注释掉这两个字段中的任何一个,则类的大小就是您期望的大小,分别为10个字节和2个字节。

Is there a way to instruct the compiler to use only 10 bytes for my class? 有没有一种方法可以指示编译器对我的类仅使用10个字节?

#pragma pack can make your structures smaller. #pragma pack可以使您的结构更小。 On the other hand, it can make retrieving the member data slower, since the alignment of the bytes is not guaranteed. 另一方面,由于不能保证字节的对齐,这会使检索成员数据的速度变慢。 As a result the compiler will need extra instructions to fetch the data from different memory locations. 结果,编译器将需要额外的指令以从不同的存储器位置获取数据。 For more info, this link has an excellent post: #pragma pack effect 有关更多信息,此链接具有出色的文章: #pragma pack effect

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM