我遇到以下情况:
//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; };
在函数g中,我想将参数(指向B的指针)转换为指向A的指针.
B实例始终包含在A实例中.
我最终得到了这个:
ptrdiff_t lag(){ A a; return (char*)&a.b-(char*)&a;} void g(B*b){ A*a=(A*)((char*)b-lag()); //Work with a }
这个解决方案让我非常不舒服.
这样的偏移计算是100%正确和便携吗?
它是否以任何方式触发未定义的行为?
编辑:std :: is_standard_layout ::值为1.