Reputation: 735
Recently I encountered code that did this:
static_assert(sizeof(void*) >= sizeof(size_t));
size_t idx = get_index_to_array();
void* ptr = (void*)idx;
Essentially using a void*
pointer provided by a third party library to store an index into an array to save an allocation.
Assuming that the pointer will neither be 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)?
Upvotes: 2
Views: 190
Reputation: 238351
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)?
It is conforming.
Since there is no compatible static cast, this explicit type conversion (colloquially called C-style cast) performs a reinterpret cast. Of this, the standard says (quoting the latest draft):
[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.
Upvotes: 2
Reputation: 7202
If, as you say, this void*
pointer will not be used for anything but being cast back to an int
, then yes, this code is fine.
The C-style cast in (void*)idx
falls back to a reinterpret_cast
when all other casts fail (such as static_cast
). Usually reinterpret cast is a dangerous thing, but it does come with the guarantee that casting to an intermediate type, then back to the original type, will always yield the original value. Thus, your code, under the stated constraints, is fine.
Upvotes: 1