简体   繁体   中英

Reversing pointer to data member

Hi I am trying to figure out if it is legal (by the C++) standard to compute an offset of a member of a class (in order to reverse it).

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;
}

Is it legal C++ to do &(parent_p->*offset) with parent_p being a nullptr ?

It's been debated for some time with no apparent outcome. However, the debate is moot with implementation-provided, standard-blessed offsetof macro.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM