C++构件参考的结构参考
给定以下设置...
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只有当您知道的事实
ar
是引用ac :: a
成员,那么您可以使用offsetOf()
(应该 return 返回0这种情况,因为a
是c
的第一个非静态数据成员,但最好不要假设)来帮助您访问c
对象,例如:在线演示
Only if you know for a fact that
ar
is referencing aC::a
member, then you can useoffsetof()
(which should return 0 in this case, sincea
is the 1st non-static data member ofC
, but best not to assume that) to help you access theC
object, eg:Online Demo