c++ - 反转指向数据成员的指针

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

您好,我想弄清楚计算类成员的偏移量(以便反转它)是否合法(根据 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;
}

parent_p 作为 nullptr 执行 &(parent_p->*offset) 是否合法?

最佳答案

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

关于c++ - 反转指向数据成员的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36480755/

相关文章:

c++ - 与共享库链接时 undefined reference

c - 我正在尝试使用 malloc 创建一个 char 数组数组,然后使用 for 填充数组

c++ - 为什么 C++ 的 NULL 通常是整数文字而不是像 C 中的指针?

c++ - unique_ptr 可以采用 nullptr 值吗?

c++ - Boost::serialize - 反序列化对象 vector ?

C++:使用宏字符串将项目转换为动态变量的简单方法?

c++ - 包含来自新文件夹 "cannot open include file - no such file or directory"的头文件

C指针问题

c - C 中的 typedef 和指向函数的指针

c++ - 为什么使用 `nullptr` 会导致性能下降 [在 LeetCode 上]?