0

With a VC++ project I have a line:

FXint realIndex = (int)m_cmbDevice->getItemData(indx);

This reads a void pointer value from combo box to an int value. In VC++ it compiles and works well. Now I have to port this to Linux and there I get a compile error

cpp:514:20: error: 
      cast from pointer to smaller type 'int' loses information
        FXint realIndex = (int)m_cmbDevice->getItemData(indx);

Now I use

std::size_t x = reinterpret_cast<std::size_t>(m_cmbDevice->getItemData(indx));
FXint realIndex = x;

My question is now, is this the right way to go?

phuclv
  • 37,963
  • 15
  • 156
  • 475
IFDev
  • 55
  • 7

1 Answers1

1
  • reinterpret_cast is dangerous and is typically used only to interpret a pointer as another kind of pointer. You should use static_cast instead
  • size_t is not necessarily big enough to store a pointer. There are already intptr_t and uintptr_t which are signed and unsigned integer types that are capable of holding a pointer
  • FXint realIndex = x; still raises a warning if x is wider than FXint, so another cast is necessary to turn off all related warnings

So you need to do this

auto x = reinterpret_cast<uintptr_t>(m_cmbDevice->getItemData(indx));
auto realIndex = (FXint)x;
phuclv
  • 37,963
  • 15
  • 156
  • 475
  • Also, casting to FXint with C-style cast is unsafe. That is where static_cast should have been used. Except, performing any cast is unsafe in the first place and the correct solution would be make sure that FXint is a sufficiently wide integer type. – eerorika Nov 30 '20 at 09:33
  • This is very good but misses that one should `#include `, and that then only guarantees to declare these types within namespace `std::`, not the global namespace. – underscore_d Nov 30 '20 at 09:48