C ++ 11:如何获取地址/对外部类的引用?

emacs让我发疯

假设以下类(C ++ 11):

class A
{
  int i;
  class B
  {
    void meth() 
    {
        // Get outer address / reference? 
    }; 
  } b;
};

哪里B永远是其中的一部分A,即没有类似的代码new B()

这意味着b.meth()将始终在外部操作A

问题:如何从外部b.meth()(与偏移始终相同,b并且在编译时已知)到达外部

樱桃DT

这可能不是最佳解决方案,而且它是非标准的,而且我敢肯定,人们会说这是个坏主意。因此,如果您只是在Internet上随机发现此内容,请不要盲目使用。但是我不确定是否存在标准解决方案。

它去了:

// Example program
#include <iostream>
#include <cstdint>

// This may not be needed if your compiler already has an offsetof macro defined
#ifndef offsetof
#define offsetof(s,m) ((::size_t)&reinterpret_cast<char const volatile&>((((s*)0)->m)))
#endif

class A
{
  public:
  int i;
  class B
  {
    public:
    void meth() 
    {
        // We basically subtract the offset of `b` within `A` from the start of `b`,
        // giving us the outer `A`'s `this`.
        A* outer = (A*)((std::uintptr_t)this - offsetof(A, b));
        std::cout << outer->i;
    }; 
  } b;
};


int main()
{
  A a;
  a.i = 123;
  a.b.meth();

  return 0;
}

// Output: 123

请注意,如果A不是标准布局类型,则此操作将失败

无论如何,我认为您应该考虑一种更好的方法来对数据结构进行建模。我张贴的是为您立即发行的创可贴。

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

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

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章