2

我想知道使用 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;
}
4

1 回答 1

4

方法3是正确的。

虽然其他人可能会给出类似的结果(至少在某些时候),但它们或多或少是不正确的。

如果指针是 32 位而不是 64 位,方法 2将出错,因为您将指针的类型强制为uint64_t.

方法 1可以工作 - 但它是不必要的,但你不需要uint64_t- 两者都是 void 指针类型。memlocaladdr

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

于 2013-01-25T00:46:06.727 回答