《C++ 对象模型内部》说,类中数据成员的偏移量总是比实际偏移量大 1,以便区分指向 0 的指针和指向第一个数据成员的指针,示例如下:
class Point3d {
public:
virtual ~Point3d();
public:
static Point3d origin;
float x, y, z;
};
//to be used after, ignore it for the first question
int main(void) {
/*cout << "&Point3d::x = " << &Point3d::x << endl;
cout << "&Point3d::y = " << &Point3d::y << endl;
cout << "&Point3d::z = " << &Point3d::z << endl;*/
printf("&Point3d::x = %p\n", &Point3d::x);
printf("&Point3d::y = %p\n", &Point3d::y);
printf("&Point3d::z = %p\n", &Point3d::z);
getchar();
}
所以为了区分下面的两个指针,一个数据成员的偏移量总是多1。
float Point3d::*p1 = 0;
float Point3d::*p2 = &Point3d::x;
上面的主要功能是尝试获取成员的偏移量来验证这个参数,它应该输出:5、9、13(考虑开头4bytes的vptr)。然而,在MS Visual Studio 2012中,输出为:
&Point3d::x = 00000004
&Point3d::y = 00000008
&Point3d::z = 0000000C
问题:MS C++ 编译器是否做了一些优化或阻止这种机制?