Suppose that we have a pointer-to-class member pointing at a field of a class. We also have a pointer to that specific field in a particular instance of the class. For example, we might have something like this:
class A {
B inner_object;
}
A* myA = /* ... */
B* ptr = &myA->inner_object;
B A::* memPtr = &A::inner_object;
Is there a way to use ptr and memPtr to recover myA? That is, if we didn’t already have an explicit pointer for myA, could we make one out of ptr and memPtr?
After a decent amount of research…
This is actually done in most industrial intrusive list implementations. It does require some hackery, however.
Boost intrusive structures use the following (and yes, it is implementation specific)
Essentially the same thing (albeit in C) as is done in the linux kernel to manage intrusive lists, with the container_of macro (but of course ptr-to-members are not used):