Search code examples
c++c++11pointer-to-memberoffsetof

Invert pointer to member (i.e. get the address of the containing struct)


I have a struct (Member) that can only be used as data member in some other struct (Container). By convention the name of the member is always m. Is there a reliable way for the member to obtain the address of the containing struct?

template<typename Struct>
struct Member;
{
  const Struct& s = ??;
                    // this - &Struct::m
};

struct Container
{
   Member<Container> m;
};

I was hoping that maybe using the pointer to member &Container::m might help to calculate back from the address of the Member object itself?


Solution

  • No, you cannot do this. You can determine the offset of m within Container and do pointer arithmetic to guess at the resulting address of the Container, but this will be:

    • unreliable
    • prone to catastrophic errors
    • UB (and therefore can cause symptoms including time travel — no, seriously!)

    It might work consistently on a few platforms if you have all optimisations disabled but, really, please, just don't.

    Either pass a pointer/reference to Container into Member<Container>'s constructor (after adding one), or further rethink your design. Why does the member need to be aware of the object encapsulating it? That is almost always wrong (though there are some passable use cases).