首页 > 解决方案 > C++11:如何获取外部类的地址/引用?

问题描述

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

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

whereB将永远是其中的一部分A,即没有new B().

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

问题:如何从外部b.meth()(它始终具有相同的偏移量b并且在编译时已知)?

标签: c++c++11

解决方案


这可能不是最好的解决方案,而且它是非标准的,我相信人们会说这是一个坏主意。所以,万一你只是在网上随机发现的,不要盲目使用。但我不确定是否存在标准解决方案。

它是这样的:

// 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不是标准布局类型,这将失败。

无论如何,我认为您应该考虑一种更好的方法来为您的数据结构建模。我发布的是针对您当前问题的创可贴。


推荐阅读