首页 > 解决方案 > 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 Inners only ever live inside Outers, 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 Inners as base subobjects (e.g. this) - I very much feel like something similar should be possible for member subobjects?

标签: c++c++14

解决方案


您应该注意,从指向成员的指针获取指向父对象的指针的问题通常是无法解决

offsetofand cast 仅适用于标准布局类型。在其他情况下,它是未定义的行为。

例如,对于多重虚拟继承,它会失败。在这种情况下,成员访问是通过比添加编译时间偏移更复杂的方式实现的。也许这实际上并不那么相关,因为它很少使用,但您明确要求符合标准。


推荐阅读