将指针转换为整数时,我应该使用 reinterpret_cast 吗?

When converting pointers to integers, should I be using reinterpret_cast?

据我了解,当从指针转换为整数时,我应该使用 reinterpret_cast,因为这让我在编译时检查整数变量是否足够大以适合指针。对吗?

而不是仅仅在我没有保证的地方转换,并且在从 32 位环境移动到 64 位环境时最终可能会截断地址?

1.reinterpret_cast 表示重新解释底层位模式。这意味着 C 中的显式转换,如:

void *vptr; 
int *iptr = (int *)(vptr);

你应该知道reinterpret_cast是不安全的,转换的正确性由你自己决定。

如果需要type-safe转换,请使用static_cast,即隐式转换或type-safe类型间转换。常用于数值类型之间

2.It可能会导致截断,使用准确的字长int-type是合适的。即 int64_t 通过包含 <cstdint>

  1. 你永远不应该这样做(有意义的例外情况非常罕见)。请解释您为什么需要这个。
  2. 指针在特定平台上具有固定大小。
  3. 标准提供与每个平台的指针大小相匹配的整数类型定义uintptr_t / intptr_t

I should be using reinterpret_cast ... Is that correct?

正确...前提是首先需要这样的演员表,这很少见。

.. because that gives me a compile-time check that the integer variable is large enough to fit a pointer. Is that correct?

不正确。与 c 风格转换相比,没有额外的警告保证。 Reinterpret_cast 是首选,因为它更明确并且不允许丢弃 const。