Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reinterpret_cast cast cost

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?

like image 727
fulmicoton Avatar asked Aug 26 '10 12:08

fulmicoton


People also ask

Is it safe to use reinterpret_cast?

reinterpret_cast is a very special and dangerous type of casting operator. And is suggested to use it using proper data type i.e., (pointer data type should be same as original data type).

What is the difference between static_cast Dynamic_cast Const_cast and reinterpret_cast?

Use static_cast as the equivalent of a C-style cast that does value conversion, or when we need to explicitly up-cast a pointer from a class to its superclass. Use const_cast to remove the const qualifier. Use reinterpret_cast to do unsafe conversions of pointer types to and from integer and other pointer types.

How does reinterpret cast work?

The reinterpret_cast allows the pointer to be treated as an integral type. The result is then bit-shifted and XORed with itself to produce a unique index (unique to a high degree of probability). The index is then truncated by a standard C-style cast to the return type of the function.

Is reinterpret cast compile time?

The dynamic cast is the only that needs to be "calculated" in run-time. All other casts are calculated in compile-time. The machine code for a static_cast is a fixed function based on the type you are casting FROM and TO. For reinterpret_cast , the machine code can be resolved in compile-time as well.


1 Answers

It's a good assumption to start with. However, the optimizer may be restricted in what it can assume in the presence of a reinterpret_cast<> or C pointer cast. Then, even though the cast itself has no associated instructions, the resulting code is slower.

For instance, if you cast an int to a pointer, the optimizer likely will have no idea what that pointer could be pointing to. As a result, it probably has to assume that a write through that pointer can change any variable. That beats very common optimizations such as storing variables in registers.

like image 57
MSalters Avatar answered Oct 12 '22 22:10

MSalters