Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert long int* to long long int*

Tags:

c++

c++11

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?

like image 783
InsideLoop Avatar asked Mar 14 '23 21:03

InsideLoop


1 Answers

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);
}
like image 62
Hcorg Avatar answered Mar 23 '23 02:03

Hcorg