“在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++编译器是否进行了某些优化或某些措施来阻止这种机制?

最佳答案

tl; dr

C++对象模型内部有一本非常古老的书,无论如何,它的大部分内容都是特定编译器的实现细节。不必担心将您的编译器与某些古老的编译器进行比较。

完整版本

An answer to the question linked to in a comment on this question很好地解决了这个问题。

关于c++ - C++中的数据成员偏移量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16254019/

10-12 22:13