简体   繁体   中英

C++ structure reference from member reference

Given the following setup...

struct A {unsigned char _data;};
struct B {unsigned char _data;};
struct C {A a; B b;};

// in this context (ar) is known to be the "a" of some C instance
A& ar = ...;
B& br = get_sister(ar); // the "b" of the same C instance that (ar) belongs to
C& cr = get_parent(ar); // the C instance that (ar) belongs to

...how do I get br and cr from ar without UB (undefined behaviour)?

Only if you know for a fact that ar is referencing a C::a member, then you can use offsetof() (which should return 0 in this case, since a is the 1st non-static data member of C , but best not to assume that) to help you access the C object, eg:

C& get_parent(A& ar)
{
    return *reinterpret_cast<C*>(reinterpret_cast<char*>(&ar) - offsetof(C, a));
}

B& get_sister(A& ar)
{
    return get_parent(ar).b;
}

Online Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM