C++构件参考的结构参考

发布于 2025-01-27 01:52:01 字数 473 浏览 3 评论 0原文

给定以下设置...

struct A {unsigned char _data;};
struct B {unsigned char _data;};
struct C {A a; B b;};

// in this context (ar) is known to be the "a" of some C instance
A& ar = ...;
B& br = get_sister(ar); // the "b" of the same C instance that (ar) belongs to
C& cr = get_parent(ar); // the C instance that (ar) belongs to

...我如何从ar ar 中获得br 没有UB(未定义的行为)?

Given the following setup...

struct A {unsigned char _data;};
struct B {unsigned char _data;};
struct C {A a; B b;};

// in this context (ar) is known to be the "a" of some C instance
A& ar = ...;
B& br = get_sister(ar); // the "b" of the same C instance that (ar) belongs to
C& cr = get_parent(ar); // the C instance that (ar) belongs to

...how do I get br and cr from ar without UB (undefined behaviour)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

2025-02-03 01:52:01

只有当您知道的事实 ar是引用a c :: a成员,那么您可以使用 offsetOf() 应该 return 返回0这种情况,因为ac的第一个非静态数据成员,但最好不要假设)来帮助您访问c对象,例如:

C& get_parent(A& ar)
{
    return *reinterpret_cast<C*>(reinterpret_cast<char*>(&ar) - offsetof(C, a));
}

B& get_sister(A& ar)
{
    return get_parent(ar).b;
}

在线演示

Only if you know for a fact that ar is referencing a C::a member, then you can use offsetof() (which should return 0 in this case, since a is the 1st non-static data member of C, but best not to assume that) to help you access the C object, eg:

C& get_parent(A& ar)
{
    return *reinterpret_cast<C*>(reinterpret_cast<char*>(&ar) - offsetof(C, a));
}

B& get_sister(A& ar)
{
    return get_parent(ar).b;
}

Online Demo

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文