简体   繁体   中英

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 . When I mouse over sizeof(myclass) (in VS), however, it reports 16 bytes. If I comment out either of the fields, the size of the class is what you'd expect, 10 bytes and 2 bytes respectively.

Is there a way to instruct the compiler to use only 10 bytes for my class?

#pragma pack can make your structures smaller. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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