从其成员子对象之一的地址计算对象的地址 [英] Computing the address of an object from the address of one of its member subobject

查看:156
本文介绍了从其成员子对象之一的地址计算对象的地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我处于以下情况:

  //这是Public 
class B {/ * usefull stuff * /};
B * f();
void g(B * b)();

//这些类只声明为f和g的翻译单位。
class Whatever1 {/ *实现细节只对f和g * /}有用;
class Whatever2 {/ *实现细节只对f和g * /}有用;
class A {
public:
Whatever1 w1;
Whatever2 w2;
B b;
};

在函数g中,我想将参数(指向B的指针)转换为指向A的指针。





与此:

  ptrdiff_t lag(){
A a;
return(char *)& ab-(char *)& a;}

void g(B * b){
A * a = ((char *)b-lag());
//使用
}

这个解决方案让我非常不舒服。



是否100%正确且可移植以执行此类偏移计算?



它以任何方式触发未定义的行为吗?



编辑:std :: is_standard_layout< A> :: value is 1。

解决方案

如果 B 总是包含在 A 中,那么在A中向B的父代添加一个反向引用可能会更加干净。如果这对于任何原因是不切实际的,那么 offsetof 会清除它一点,但否则的方法是有效的,如果有点c-ish。

  void g(B * b){
A * a =(A *)((char *)b)-offsetof
//使用
}


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.

解决方案

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
}

这篇关于从其成员子对象之一的地址计算对象的地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆