为什么在类中使用uint64_t时需要比2 uint32_t更多的内存?如何防止这种情况? [英] Why does an uint64_t needs more memory than 2 uint32_t's when used in a class? And how to prevent this?

查看:480
本文介绍了为什么在类中使用uint64_t时需要比2 uint32_t更多的内存?如何防止这种情况?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以下面的代码为例。

  #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;
}

列印

  20 
24
8
4


$ b b

所以很容易看到一个uint64_t和两个uint32_t一样大,为什么类2有4个额外的字节,除非用两个uint32_t替换uint64_t。 b $ b

解决方案

正如所指出的,这是由于

 <$ c $ 

c> #pragma pack(1)

class ... {

};
#pragma pack(pop)

它告诉你的编译器不会对齐到8个字节,但是到一个字节。 pop命令关闭它(这是非常重要的,因为如果你这样做的标题,有人包括你的标题,可能会发生非常奇怪的错误)


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.

解决方案

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)

这篇关于为什么在类中使用uint64_t时需要比2 uint32_t更多的内存?如何防止这种情况?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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