Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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)?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Only if you know for a fact that ar is referencing a C::a member, then you can use offsetof() (which should be 0 in this case, since a is the 1st member, 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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading