本文主要以示例说明C++对象数据成员存储布局,有关理论知识,请参考Data语意学。
一、数据成员的布局
1.1、无继承
#include <iostream>
using namespace std;
class X
{
public:
int a = 0;
static int staticx;
int b = 1;
};
int X::staticx = 42;
class Y
{
public:
int a = 0;
static int staticy;
public:
int b = 1;
};
int Y::staticy = 43;
int main()
{
X x;
cout << "X:" << endl;
cout << "sizeof(X) = " << sizeof(X) << endl;
cout << "vptr address: " << (&x) << endl;
cout << "x.a address: " << &x.a << endl;
cout << "x.b address: " << &x.b << endl;
cout << "x.staticx address: " << &x.staticx << endl;
Y y;
cout << "\nY:" << endl;
cout << "sizeof(Y) = " << sizeof(Y) << endl;
cout << "vptr address: " << (&y) << endl;
cout << "y.a address: " << &y.a << endl;
cout << "y.b address: " << &y.b << endl;
cout << "y.staticy address: " << &y.staticy << endl;
return 0;
}
程序运行结果如下:
从上述结果可以看出:非静态数据成员在类对象中的排列顺序将和其被声明的顺序一样,任何中间介入的静态数据成员都不会被放进对象布局之中。在上述例子中,X和Y对象是由两个int组成的,顺序是a、b。
C++标准要求,在同一个access section(也就是private、public、protected等区段)中,成员的排列只需符合"较晚出现的成员在类对象中有较高的地址"这一条即可。
C++编译器也允许编译器将多个access section之中的数据成员自由排列,不必在乎它们出现在类声明中的顺序。
1.2、单一继承
#include <iostream>
using namespace std;
class X
{
public:
int ax = 0;
static int staticx;
int bx = 1;
char cx = 'a';
};
int X::staticx = 42;
class Y :public X
{
public:
int ay = 0;
static int staticy;
public:
int by = 1;
};
int Y::staticy = 43;
int main(