最近我遇到了这样做的代码:
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/