October 11th, 2012, 01:17 PM
I've read that using reinterpret_cast<> should rarely (if ever) be used. So, what is the proper thing to do in a case like this...
This, of course, generates an error.
uint64_t u = ; // Some unsigned int64 calculation
int64_t* i = &u;
error: invalid conversion from 'uint64_t*' to type 'int64_t*'
And this generates the following error.
int64_t* i = static_cast<int64_t*> (&u);
error: invalid static_cast from type 'uint64_t*' to type 'int64_t*'
This works but is considered bad practice since reinterpret_cast is really analogous to the old 'c' casting style (i.e. (int64_t*) &u In other words, there are no CPU instructions generated, it is simply a compiler directive indicating the bits are to be interpreted as the new type.
int64_t* i = reinterpret_cast<int64_t*> (&u);
It appears the solution would be this.
And this is what I have done for quite some time when a situation like this arises. However, what is this really doing? Isn't this analogous to the reinterpret_cast (aside from the fact that compiler instructions are really being generated)? But anything can be cast to a void*, and then from a void* to any other type*. So I assume the underlying bits are not translated to and from the intermediate void* type. Is this true? If so, then it appears you are accomplishing nothing as the internal bits for the data type are not translated.
int64_t* i = static_cast<int64_t*> (static_cast<void*> (&u));
Is this really the appropriate thing to do? If anyone can help enlighten me it would be greatly appreciated. Thanks.
October 11th, 2012, 01:42 PM
Re: Casting clarification
Checking the standard concerning reinterpret_cast:
Therefore, in your example, static_cast<int64_t*>(static_cast<void*>(&u)) is equivalent to reinterpret_cast<int64_t*>(&u).
Originally Posted by C++11 Clause 5.2.10 Paragraph 7
Click Here to Expand Forum to Full Width
This is a CodeGuru survey question.