Calculation of the address of an object at the address of one of its subobjects

I am in the following situation:

//This is Public class B{/*usefull stuff*/}; B*f(); void g(B*b)(); //Those classes are only declared the translation unit of f and g. class Whatever1{/*Implementation details only useful to f and g*/}; class Whatever2{/*Implementation details only useful to f and g*/}; class A{ public: Whatever1 w1; Whatever2 w2; B b; }; 

In function g, I want to convert a parameter (pointer to B) to a pointer to A.

B instances are always wrapped in instances of A.

I ended up with this:

 ptrdiff_t lag(){ A a; return (char*)&a.b-(char*)&a;} void g(B*b){ A*a=(A*)((char*)b-lag()); //Work with a } 

This decision makes me very uncomfortable.

Is it 100% correct and portable to perform displacement calculations like this?

Does Undefined behavior cause behavior?

Edit: std :: is_standard_layout <A> :: value is 1.

+6
source share
1 answer

If a B always contained inside A , then it can be much easier to add a back reference to the parent element B inside A. If this is impractical for some reason, then offsetof will clear it a bit, but otherwise the approach is valid if multiple c-ish.

 void g(B*b){ A* a = (A*)(((char*)b)-offsetof(class A,b)); //Work with a } 
+2
source

Source: https://habr.com/ru/post/959368/


All Articles