Is it possible to get a pointer to one subobject via a pointer to a different, unreleated subobject?

前端 未结 1 653
我寻月下人不归
我寻月下人不归 2020-12-16 08:41

Look at this simple code:

struct Point {
    int x;
    int y;
};

void something(int *);

int main() {
    Point p{1, 2};

    something(&p.x);

    ret         


        
相关标签:
1条回答
  • 2020-12-16 09:42

    This is perfectly well-defined:

    void something(int *x) {
        reinterpret_cast<Point*>(x)->y = 42;
    }
    

    The Point object (p) and its x member are pointer-interconvertible, from [basic.compound]:

    Two objects a and b are pointer-interconvertible if:

    • [...]
    • one is a standard-layout class object and the other is the first non-static data member of that object, or, if the object has no non-static data members, any base class subobject of that object ([class.mem]), or:
    • [...]

    If two objects are pointer-interconvertible, then they have the same address, and it is possible to obtain a pointer to one from a pointer to the other via a reinterpret_­cast.

    That reinterpret_cast<Point*>(x) is valid and does end up with a pointer that points to p. Hence, modifying it directly is fine. As you can see, the standard-layout part and the first non-static data member part are significant.


    Although it's not like the compilers in question optimize out the extra load if you pass a pointer to p.y in and return p.x instead.

    0 讨论(0)
提交回复
热议问题