Am I safe to assume that the offset of a data member (offsetof(mystruct, myfield)
) is numerically equal to the raw value of a member pointer retrieved with &mystruct::myfield
, or is it implementation dependent?
Asked
Active
Viewed 934 times
1

Lorenzo Pistone
- 5,028
- 3
- 34
- 65
-
No is should not be assumed so. You forget about the overhead(memory) the compiler may insert for managing the memory so allocated for the object. – DumbCoder Jan 30 '12 at 16:35
-
3A better question would be: since you know the two forms, why would you *not* use the pointer to member ? :) – Matthieu M. Jan 30 '12 at 16:41
-
I'm actually considering to use pointer to members, as my program does some low level tricks with offsetof, and I want to "elevate" them to a more standard form. – Lorenzo Pistone Jan 30 '12 at 16:51
-
4From page 7 here: http://www.agner.org/optimize/calling_conventions.pdf "Borland compilers add an offset of 1 to data member pointers in order to distinguish a pointer to the first data member from a NULL pointer, represented by 0. The other compilers have no offset, but represent a NULL data member pointer by the value -1." So there's a very specific example of when you can't rely on it, in case you were wondering if this was simply academic. – BoBTFish Jan 30 '12 at 16:58
2 Answers
3
No; the implementation of a pointer-to-member is not specified, and there is no defined conversion to get the "raw" value.

Mike Seymour
- 249,747
- 28
- 448
- 644
1
Formally, it is implementation-dependent, of course. In real life, yes, the most popular implementation of pointer-to-data-member pointers is (or is based on) plan-and-simple offset, i.e. the same thing that offsetof
evaluates to.
Some implementations use the exact offset, resorting to 0xFFF...
pattern to represent the null-pointer value. Some implementatiuons reserve 0x000...
pattern for null-pointer value, while incrementing all "non-null" offsets by 1
.

AnT stands with Russia
- 312,472
- 42
- 525
- 765