在C++中从内部类对象获取外部类对象

Getting hold of the outer class object from the inner class object in C++

本文关键字:对象 获取 外部 内部类 C++      更新时间:2023-10-16

>问题

我在 Java 上看到了这个问题,它允许您从嵌套对象中获取指向外部对象的指针。

但是,如何在C++中实现这一点呢?

不满意的解决方案:

存储指向每个对象的指针:(内存效率不高(

class Outer {
private:
int i;
class Inner {
int j;
Outer *outer;
};
Inner items[1000];
};

将数组包装在类中:(增加不必要的 (?( 复杂性(

class Outer {
private:
int i;
class Inner_array {
class Inner {
int j;
};
Inner items[1000];
// Build an interface around the array
typedef Inner (&array)[1000]; 
operator array();
// etc...
};

Inner items[1000];
Outer *outer;
};

这里有一个节省空间的想法:

struct Outer {
int i;
struct Inner {
int j;
uint16_t where;
Outer& outer() {
Inner* first = this - where;
char* addr = reinterpret_cast<char*>(first) - offsetof(Outer, items);
return *reinterpret_cast<Outer*>(addr);
}
};
Inner items[1000];
Outer() {
for (uint16_t ii = 0; ii < 1000; ++ii)
items[ii].where = ii;
}
};

如果你使用的是具有 32 位整数的 64 位计算机,这会将sizeof(Inner)从 16 个字节减少到 8 个字节(不打包(或 12 到 6 个字节(不打包(。

如果你想节省更多的空间,你可以这样做:

struct Outer {
int i;
struct Inner {
int j;
Outer& outer() {
Inner* sentinel = this;
while (sentinel.j != INT_MIN)
--sentinel;
char* addr = reinterpret_cast<char*>(sentinel) - offsetof(Outer, sentinel);
return *reinterpret_cast<Outer*>(addr);
}
};
Inner sentinel = {INT_MIN};
Inner items[1000];
};

但是outer()是 O(n( 而不是 O(1(,您必须确保INT_MIN(或某些哨兵值(永远不会在items中使用。