c++ - C++: Get adress of complete object containing member subobject
问题描述
I have two classes, roughly defined like this:
class Inner {
public:
bool is_first;
};
class Outer {
public:
char some_other_member;
Inner first;
Inner second;
}
I known that Inner
s only ever live inside Outer
s, and that the respective bool flag will be set to true
if and only if the respective object is the first
member, not the second
.
I am looking for a standard-compliant way of deriving a pointer to the Outer
object containing some Inner
object. Of course I could just store a pointer inside every Inner
object, but since the Inner
class is very small and I have lots of them, that seems like a waste of memory (and thus precious cache).
Obviously, the compiler should know the memory offset between first
, second
and the containing Outer
object. The question is: Is there a standard-compliant way of telling the compiler "get that offset, subtract it from the pointer to Inner
and make it an Outer
pointer"?
I know I could use casting to void
if Outer
would contain the Inner
s as base subobjects (e.g. this) - I very much feel like something similar should be possible for member subobjects?
解决方案
您应该注意,从指向成员的指针获取指向父对象的指针的问题通常是无法解决的。
offsetof
and cast 仅适用于标准布局类型。在其他情况下,它是未定义的行为。
例如,对于多重虚拟继承,它会失败。在这种情况下,成员访问是通过比添加编译时间偏移更复杂的方式实现的。也许这实际上并不那么相关,因为它很少使用,但您明确要求符合标准。
推荐阅读
- javascript - 如何在 Yarn PnP 模式下使用 Rollup+Babel 转译依赖的 js 文件?
- docker - 使用 docker compose 将 API 连接到数据库
- java - Java 线程调度和对象锁定。线程优先级?
- android - Android 11 中的位置变化将如何影响后台请求?
- java - 多线程中的休眠会话
- python - 当我们更改数组值时,它如何影响 json 文件的结果
- salesforce - Salesforce Connected App 忽略 http ACS 值并改为重定向到 https
- javascript - 从角度的服务人员调用函数?
- xamarin.forms - 来自 appcenter 的 android 11 设备上的应用未安装错误
- django - 'TypeError' 对象没有属性 ''