问题
I am working through a book (Foundations Of Game Engine Development By Eric Lengyel) and the book is writing out some vector operations in c++, here is the snippet:
struct Vector3D
{
float x, y, z;
Vector3D() = default;
Vector3D(float a, float b, float c)
{
x = a;
y = b;
z = c;
}
float& operator [](int i)
{
return((&x)[i]);
}
};
im particularly concerned with this piece:
float& operator [](int i)
{
return((&x)[i]);
}
Now I would expect this code to return x, no matter what index is entered. However the corresponding variable (x, y, or z) is output depending on the input. Why is this? Thanks for the help.
回答1:
For a few moments, let's ignore the foul smell of the way the function has been implemented.
The question is, how does it ever work?
If you look at the member variables of an object of the class, when there is no padding between members, they are laid out in memory as:
+-----+-----+-----+
| x | y | z |
+-----+-----+-----+
With such a layout, the object appears as though it is an array of float
s.
If you use:
float* ptr = &x;
ptr
points to the first element of such an array.
ptr[0]
evaluates to the first element of the array, which is the same as x
.ptr[1]
evaluates to the second element of the array, which is the same as y
.ptr[2]
evaluates to the third element of the array, which is the same as z
.
That's why
return((&x)[i]);
works most of the time, even though such code is cause for undefined behavior per the standard.
来源:https://stackoverflow.com/questions/48031228/how-does-this-implementation-of-operator-function-work