从其成员子对象的地址计算对象的地址

 hanjing0118 发布于 2023-02-12 18:07

我遇到以下情况:

//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.

撰写答案
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有