c++ - 根据其成员子对象之一的地址计算对象的地址

标签 c++ c++11 offset language-lawyer undefined-behavior

我处于以下情况:

//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< A >::value is 1.

最佳答案

如果 B 总是包含在 A 中,那么在 A 中添加对 B 的父级的反向引用可能会更简洁。如果这对于任何情况都不切实际原因,然后 offsetof 会稍微清理一下,但除此之外,如果有点 c-ish,该方法是有效的。

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

关于c++ - 根据其成员子对象之一的地址计算对象的地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20395008/

相关文章:

c++ - 如何在另一个#define 中实现#define?

c++ - 为什么 one-definition-rule-use (odr-use) 取决于上下文?

c++ - 为什么会超出内存限制?

node.js - Node.js 模块 'time' 的时区问题

offset - SwiftUI:手势和偏移未按预期工作

jquery - 溢出 Div 中的偏移量问题

c++ - 你如何在 C++ 中读入一个 3 字节大小的值作为整数?

用于在指向相同大小的类型的指针之间进行转换的 C++ 转换?

c++ - 如何在 C++ 中的混合字符串整数行中提取特定整数

C++ - 使用initializer_list作为参数的模板函数