【问题标题】:Reversing pointer to data member反转指向数据成员的指针
【发布时间】:2016-07-28 14:30:58
【问题描述】:

您好,我想弄清楚计算类成员的偏移量(以反转它)是否合法(通过 C++)标准。

class A
{
public:
    int a, b, c, d;
};

template <typename ParentClass, typename T>
ParentClass const * offset_this_pointer(T const * member_ptr, T ParentClass::* offset)
{
    ParentClass const * parent_p = nullptr;
    // we are technically dereferencing a NULL pointer here,
    // but we are not using the result, only taking the address of it
    // This works and yields the desired result in MSVC 2010, gcc 4.9.2 and Solaris10 compilers.
    T const * offset_p = &(parent_p->*offset);

    return reinterpret_cast<ParentClass const *>((uintptr_t)member_ptr - (uintptr_t)(offset_p));
}

int main()
{
    A a;

    assert(&a == offset_this_pointer(&a.b, &A::b)); // passes

    return 0;
}

&amp;(parent_p-&gt;*offset)parent_p 作为nullptr 一起使用C++ 是否合法?

【问题讨论】:

    标签: c++ pointers nullptr member-pointers data-member-pointers


    【解决方案1】:

    已经争论了一段时间,没有明显的结果。然而,关于实现提供的、受标准祝福的offsetof 宏的争论是没有实际意义的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-27
      • 1970-01-01
      • 2013-03-10
      • 1970-01-01
      • 1970-01-01
      • 2018-03-24
      • 1970-01-01
      相关资源
      最近更新 更多