如何计算类和填充的大小 [英] How do I calculate size of class and padding
本文介绍了如何计算类和填充的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
#include "stdafx.h"
#include"iostream"
class test
{
public:
int a ;//size of integer is 4 byte
double b;//size of double is 8 byte
char ch[8+1];///9 size of char array is 9 byte
};
int _tmain(int argc, _TCHAR* argv[])
{
test obj;
std::cout<<sizeof(obj.a)<<std::endl;
std::cout<<sizeof(obj.b)<<std::endl;
std::cout<<sizeof(obj.ch)<<std::endl;
std::cout<<sizeof(test); //why size of class is 32 byte??
int p;
std::cin>>p;
return 0;
}
输出:
4
8
9
32
我真的不明白为什么班级规模大小32字节。如果我只计算三个数据成员的大小,它只有21个字节。我确实理解使用了一些字节概念但我不明白字节填充是如何工作的。
任何人都可以告诉我这个。如果我改变了成员的顺序数据类的大小将如何变化以及为什么?
问候,
Joy
output:
4
8
9
32
I really do not understand why size of class is 32 byte. if I calculate size of three data members alone its just 21 byte only. I do understand that some byte concept is used but I do not understand how byte padding works.
Can anybody make me clear on this.And if I change order of member data how size of class will get changed and why?
Regards,
Joy
推荐答案
Padding。
Microsoft C ++编译器(正如Peter给你的链接所说)总是将类填充到一个合理大小的内存访问。
如果你取出了char数组,你会发现它是16个字节。
如果你把它减少到:
Padding.
The Microsoft C++ compiler (as the link Peter gave you says) always pads classes to a "sensible" size for memory access.
If you take out the char array, you will find it is 16 bytes.
If you cut it down to:
class test
{
public:
int x;
char c;
};
你会发现它被填充到8个字节。
You will find it is padded to 8 bytes.
这篇关于如何计算类和填充的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文