嗨,我正试图弄清楚(根据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;
}
用C++做&(parent_p->*offset)
而parent_p
是nullptr
合法吗?
争论了一段时间,但没有明显的结果。然而,对于所提供的实现、标准支持的offsetof
宏,争论是没有意义的。