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

科斯塔斯

问题

在 Java 上看到了这个问题,它允许您Nested object 中获取指向Outer 对象的指针

但是你怎么能在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_MINitems.

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章