reinterpret_cast cast cost

Viewed 15543

My understanding is that C++ reinterpret_cast and C pointer cast is a just a compile-time functionality and that it has no performance cost at all.

Is this true?

7 Answers

I was looking at my assembler code before and after reinterpret casting signed char as unsigned char. The instructions grew by about 3 or four more instructions.

int main()
{
 signed char i = 0x80;
 (unsigned char&)i >>= 7;
 return i;
}

I was casting to unsigned char to make the compiler use SHL instruction, rather than SAR instruction, so that newly shifted shift in bits would be zer0s instead of var i signed bit value.

The compiler still and seems to always use SAR instruction. But the reinterpret casting made the compiler add more instructions. 3 to 4 more instructions!

I was concerned why my unicode function for converting UTF8 to UTF16 string was almost 3 times slower than Win32 MultiByteToWideChar(). Now I am worried that casting is one of the main factors.

Which is IRONIC, as we use reinterpret cast for speed.

Related