Today there are students in school asking how to get the address offset of member variables in a class, this should be a curious question for many beginners of C + +. I used to have this kind of demand when I was in school. Forget to write "strange program", anyway, you need to get the address offset of the member variable of a class.
In fact, the problem is very simple, if you understand the C + + class object Memory distribution, this is not a problem at all. I gave him an example:
struct A
{
int i;
};
& (*) 0)->i; This allows you to get to the offset. He said he didn't understand, OK, let's have a concrete talk.
If you define a variable A; We all know that &a indicates that the first address of variable a,& (A.I) represents the address of the variable i, then the & (A.I) minus &a does not get the offset of I?
Yes, it's that simple. So what does this example & (A *) 0 have to do with->i;?
The Address for & (A *) 0) is 0, so & ((A *) 0)->i equals & ((A *) 0)->i minus 0.
The student was even more curious, why & (A *) 0)->i no problem? This example does not allocate memory for the object of a, so how can I get its address?
Yes, there is no memory allocated here, but in this case we do not require memory and we do not operate on the memory, so it will not lead to a crash.
& ((a) 0)->i just uses the compiler to figure out its address for us. When the compiler wants to use a member variable, it gets the address of the member variable based on the object's first address plus the member's offset. When the object's first address is 0 o'clock, the resulting member variable address is its offset.
Come here, understand!
Get the address offset of a C + + class member variable