How does this implementation of operator[] function work?

浪子不回头ぞ 提交于 2020-01-05 04:58:31

问题


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 floats.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!