Computing the address of an object from the address of one of its member subobject

为君一笑 提交于 2019-12-22 05:16:49

问题


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 the parameter (a pointer to B) to a pointer to A.

B instances are always wrapped in A instances.

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 solution makes me very unconfortable.

Is it 100% correct and portable to do offset computations like this ?

Does it triggers Undefined Behavior in any way ?

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


回答1:


If a B is always contained within an A, then it might be much cleaner to add a back reference to B's parent inside A. If that is impractical for whatever reason, then offsetof will clean it up a little, but otherwise the approach is valid, if somewhat c-ish.

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


来源:https://stackoverflow.com/questions/20395008/computing-the-address-of-an-object-from-the-address-of-one-of-its-member-subobje

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!