On my platform, both long int and long long int are the same (64 bits). I have a pointer to a long int and I want to convert it to a pointer to a long long int. The following code
static_cast<long long int*>(pointer);
is not allowed. What is the correct way to do that in C++11?
You have to force 're-interpretation' of pointer:
reinterpret_cast<long long int*>(pointer);
Such cast means to compiler "stop checking, I know how better interpret binary data in that expression". So whenever making reinterpret_cast
- check twice your knowledge of platform, memory alignment etc. Write some simple unit tests etc, run them through valgrind or address sanitizer.
So think now, if you really need to cast such pointer. Often redesign of function etc. can resolve such issue (for example if you only need data from pointed value - store it in some additional variable etc.).
You can also try to force a little bit checking by compiler:
template <typename Dest, typename Src>
Dest* safe_pointer_cast(Src* src)
{
static_assert(sizeof(Src) == sizeof(Dest), "size of pointed values differ");
static_assert(alignof(Src) == alignof(Dest), "alignment different");
return reinterpret_cast<Dest*>(src);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With