c++ - 将任意整数转换为 void*

标签 c++ pointers integer c++17 reinterpret-cast

最近我遇到了这样做的代码:

static_assert(sizeof(void*) >= sizeof(size_t));

size_t idx = get_index_to_array();
void* ptr = (void*)idx;

本质上是使用第三方库提供的 void* 指针将索引存储到数组中以保存分配。

假设该指针在任何时候都不会被取消引用,也不会被释放/删除,并且只会用于转换回原始值,此代码是否严格符合 C++(根据 C++17 标准,如果这很重要) )?

最佳答案

Asuming that the pointer will not get dereferenced nor freed/deleted at any point and will be only used to cast back to the original value, is this code strictly conforming C++ (per the C++17 standard, if that matters)?

符合要求。

由于没有兼容的静态强制转换,因此这种显式类型转换(通俗地称为 C 风格强制转换)会执行重新解释强制转换。其中,标准表示(引用最新草案):

[expr.reinterpret.cast]

A value of integral type or enumeration type can be explicitly converted to a pointer. A pointer converted to an integer of sufficient size (if any such exists on the implementation) and back to the same pointer type will have its original value; mappings between pointers and integers are otherwise implementation-defined.

关于c++ - 将任意整数转换为 void*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57734303/

相关文章:

c++ - std::regex_replace 期间的堆栈溢出

c - 访问超出为指针分配的内存的索引

C++ 访问器——我应该返回一个指向成员变量的指针还是返回实际的成员变量本身?

javascript - 从 Javascript 中的字符串中提取多个整数

c++ - uint128_t 没有命名类型

ruby - 在 Ruby 中将整数转换为带符号的字符串

c++ - 为处于挂起状态的线程调用 TerminateThread C++

c++ - 相当于 clojure 中 C++ 的 stable_partition?

c++ - C++ 中的可扩展和动态图形可视化库

c++ - * token 之前的预期初始化程序