将任意整数转换为 void*
Casting an arbitrary integer to void*
最近我遇到了这样做的代码:
static_assert(sizeof(void*) >= sizeof(size_t));
size_t idx = get_index_to_array();
void* ptr = (void*)idx;
本质上是使用第三方库提供的void*
指针将索引存储到数组中以节省分配。
假设指针在任何时候既不会被解除引用也不会 freed/deleted,并且只会被用于转换回原始值,此代码是否严格符合 C++(根据 C++17 标准, 如果这很重要)?
如果像您所说的那样,这个 void*
指针除了被转换回 int
之外不会用于任何其他用途,那么是的,这段代码没问题。
当所有其他类型转换都失败时(例如static_cast
),(void*)idx
falls back to a reinterpret_cast
中的C 风格类型转换。通常重新解释转换是一件危险的事情,但它确实保证转换为中间类型,然后返回原始类型,将始终产生原始值。因此,在规定的约束下,您的代码没有问题。
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.
最近我遇到了这样做的代码:
static_assert(sizeof(void*) >= sizeof(size_t));
size_t idx = get_index_to_array();
void* ptr = (void*)idx;
本质上是使用第三方库提供的void*
指针将索引存储到数组中以节省分配。
假设指针在任何时候既不会被解除引用也不会 freed/deleted,并且只会被用于转换回原始值,此代码是否严格符合 C++(根据 C++17 标准, 如果这很重要)?
如果像您所说的那样,这个 void*
指针除了被转换回 int
之外不会用于任何其他用途,那么是的,这段代码没问题。
当所有其他类型转换都失败时(例如static_cast
),(void*)idx
falls back to a reinterpret_cast
中的C 风格类型转换。通常重新解释转换是一件危险的事情,但它确实保证转换为中间类型,然后返回原始类型,将始终产生原始值。因此,在规定的约束下,您的代码没有问题。
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.