使用reinterpret_cast的正确方法

时间:2013-01-25 00:34:00

标签: c++

我想知道使用reinterpret_cast的正确方法。我有一个场景,我必须使用void **指针保存类型uint64_t的地址(比如0x1122)(参见下面的示例代码)。所有这三种方式似乎都有效。他们之间有什么区别?其中一个其实是错的吗?另外,这样做的最佳方式是什么?谢谢!

#include <iostream>
#include <cstdint>

using std::cout;
using std::endl;

int main()
{
    void **localAddr;
    void *mem;
    localAddr = &mem;
    // The above three lines is the setup that I have to work with.
    // I can't change that. Given this setup, I need to assign an
    // address 0x1122 to mem using localAddr.

    // Method 1
    *localAddr = reinterpret_cast<uint64_t*>(0x1122);
    cout << mem << endl; // Prints 0x1122

    // Method 2
    *(reinterpret_cast<uint64_t*>(localAddr)) = 0x1122;
    cout << mem << endl; // Prints 0x1122

    // Method 3
    *localAddr = reinterpret_cast<void*>(0x1122);
    cout << mem << endl; // Prints 0x1122

    return 0;
}

1 个答案:

答案 0 :(得分:4)

方法3 是正确的。

虽然其他人可能会给出类似的结果(至少是somteimes),但他们或多或少都是不正确的。

如果指针是32位而不是64位,那么

方法2 将会出错,因为您强制指针的类型为uint64_t

方法1 会有效 - 但这是不必要的,但您不需要uint64_t - memlocaladdr都是无效指针类型。

希望你能得到这份工作......