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());
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.
source share