Why does an uint64_t needs more memory than 2 uint32_t's when used in a class? And how to prevent this?

↘锁芯ラ 提交于 2019-12-22 05:33:22

问题


I have made the following code as an example.

#include <iostream>

struct class1
{

    uint8_t     a;
    uint8_t     b;
    uint16_t    c;
    uint32_t    d;
    uint32_t    e;

    uint32_t    f;
    uint32_t    g;
};

struct class2
{

    uint8_t     a;
    uint8_t     b;
    uint16_t    c;
    uint32_t    d;
    uint32_t    e;

    uint64_t    f;
};

int main(){
    std::cout << sizeof(class1) << std::endl;
    std::cout << sizeof(class2) << std::endl;
    std::cout << sizeof(uint64_t) << std::endl;
    std::cout << sizeof(uint32_t) << std::endl;
}

prints

20
24
8
4

So it's fairly simple to see that one uint64_t is as large as two uint32_t's, Why would class 2 have 4 extra bytes, if they are the same except for the substitution of two uint32_t's for an uint64_t.


回答1:


As it was pointed out, this is due to padding.

To prevent this, you may use

#pragma pack(1)

class ... {

};
#pragma pack(pop)

It tells your compiler to align not to 8 bytes, but to one byte. The pop command switches it off (this is very important, since if you do that in the header and somebody includes your header, very weird errors may occur)




回答2:


The rule for alignment (on x86 and x86_64) is generally to align a variable on it's size.

In other words, 32-bit variables are aligned on 4 bytes, 64-bit variables on 8 bytes, etc.

The offset of f is 12, so in case of uint32_t f no padding is needed, but when f is an uint64_t, 4 bytes of padding are added to get f to align on 8 bytes.

For this reason it is better to order data members from largest to smallest. Then there wouldn't be any need for padding or packing.



来源:https://stackoverflow.com/questions/26381206/why-does-an-uint64-t-needs-more-memory-than-2-uint32-ts-when-used-in-a-class-a

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!