《Inside the C++ Object Model》说,类中数据成员的偏移量总是比实际偏移量多 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
Inside the C++ Object Model 是一本很老的书,无论如何,它的大部分内容都是特定编译器的实现细节。不要担心将您的编译器与某些古老的编译器进行比较。
完整版
An answer to the question linked to in a comment on this question很好地解决了这个问题。
The offset of something is how many units it is from the start. The first thing is at the start so its offset is zero.
[...]
Note that the ISO standard doesn't specify where the items are laid out in memory. Padding bytes to create correct alignment are certainly possible. In a hypothetical environment where ints were only two bytes but their required alignment was 256 bytes, they wouldn't be at 0, 2 and 4 but rather at 0, 256 and 512.
And, if that book you're taking the excerpt from is reallyInside the C++ Object Model
, it's getting a little long in the tooth.The fact that it's from '96 and discusses the internals underneath C++ (waxing lyrical about how good it is to know where the
vptr
is, missing the whole point that that's working at the wrong abstraction level and you should never care) dates it quite a bit.[...]
The author apparently led the cfront 2.1 and 3 teams and, while this books seems of historical interest, I don't think it's relevant to the modern C++ language (and implementation), at least those bits I've read.
关于c++ - C++ 中的数据成员偏移量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16254019/