什么是C++中的数据结构填充,如何检查填充字节数?
class a { public: int x; int y; int z; };
class a { public: int x; int y; int z; };
int
在 4 字节边界上。因此,例如一个 int
可以从内存位置 0x4000
开始,但不能从 0x4001
开始。所以如果您定义了一个类:class a
{
public:
char c;
int i;
};
struct A
{
char c;
int i;
};
int main(int argc, char *argv[])
{
A a;
cout << "sizeof struct = " << sizeof(A) << endl;
cout << "sizeof items = " << sizeof(a.c) + sizeof(a.i) << endl;
return 0;
}
填充是出于性能考虑而进行的 - 请参阅此文章数据结构对齐以获取更多信息。
要查看编译器是否对您的数据结构进行了填充,您可以编写一个简单的程序:
#include <iostream>
class a {
public:
int x;
int y;
int z;
};
int main()
{
std::cout << sizeof(a) << std::endl; // print the total size in bytes required per class instance
a anInstance;
std::cout << &anInstance.x << std::endl; // print the address of the x member
std::cout << &anInstance.y << std::endl; // as above but for y
std::cout << &anInstance.z << std::endl; // etc
}
我添加了公共声明以避免编译器错误 - 这不会影响大小或填充。
编辑:在我的 MacBook Air 上运行此代码将输出以下内容: 12 0x7fff5fbff650 0x7fff5fbff654 0x7fff5fbff658
这表明在我的机器上,总大小为12字节,每个成员相隔4字节。整数每个占用4字节(可以使用sizeof(int)确认)。没有填充。
尝试在您的类中使用不同的成员进行测试,例如:
class b {
public:
char w;
char x[6];
int y;
long long z;
};
哈哈,只需创建两个相同的结构体,将其中一个打包即可 例如:
struct foo {
int a;
char b;
int c;
}
struct bar {
int a;
char b;
int c;
} __attribute__((__packed__));
sizeof(foo) - sizeof(bar)
会给你填充的数量。或者像Duck建议的那样手动计算。