Suppose there's a structure
struct Thing { int a; bool b; };
and I get a pointer to member b
of that structure, say as parameter of some function:
void some_function (bool * ptr) { Thing * thing = /* ?? */; }
How do I get a pointer to the containing object? Most importantly: Without violating some rule in the standard, that is I want standard defined behaviour, not undefined nor implementation defined behaviour.
As side note: I know that this circumvents type safety.
The pointer to member operators . * and ->* are used to bind a pointer to a member of a specific class object. Because the precedence of () (function call operator) is higher than . * and ->* , you must use parentheses to call the function pointed to by ptf .
To access a member function by pointer, we have to declare a pointer to the object and initialize it (by creating the memory at runtime, yes! We can use new keyboard for this). The second step, use arrow operator -> to access the member function using the pointer to the object.
The "arrow" operator -> is used to dereference pointers to objects to get their members. So if you have a pointer an object in the variable ui and the object has a member pushButton then you can use ui->pushButton to access the pushButton member.
If you are sure that the pointer is really pointing to the member b
in the structure, like if someone did
Thing t; some_function(&t.b);
Then you should be able to use the offsetof
macro to get a pointer to the structure:
std::size_t offset = offsetof(Thing, b); Thing* thing = reinterpret_cast<Thing*>(reinterpret_cast<char*>(ptr) - offset);
Note that if the pointer ptr
doesn't actually point to the Thing::b
member, then the above code will lead to undefined behavior if you use the pointer thing
.
void some_function (bool * ptr) { Thing * thing = (Thing*)(((char*)ptr) - offsetof(Thing,b)); }
I think there is no UB.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With