C++: How to find host object from pointer to member variable

823 Views Asked by At

Here we have our simple node struct which might be used to implement a double linked list.

template <class T>
struct node {

    node<T> *prev = NULL;
    node<T> *next = NULL;
    T data;
};

Supposing we don't know or have reference to a node object/instance, but we do have a pointer to it's data member. T data;

How can the host node object be referenced/found from the pointer to it's data member ?

1

There are 1 best solutions below

0
On BEST ANSWER

Elaborating on StenSoft comment, if you only know the value of the data member, you won't be able to get the struct containing it.

But if you know its address, say T** member_addr you can find the node :

void * ma = static_cast<void *>(member_addr); // convert pointer to void * : legal
intptr_t ima = static_cast<intptr_t>(ma); // convert void * to intptr_t : legal
intptr_t ina = ima - offsetof(struct node, data); // legal by definition of offestof
void * na = static_cast<void *>(ina); // convert intptr_t to void * : legal
struct node *pn = static_cast<node *>(na); // convert void * to pointer : legal provided the initial void * pointer points to a correct object

Of course all that is only legal for C++11 or above.