Why would a performance hit? They perform the same functionality as C cast. The only difference is that they absorb more errors during compilation and are easier to find in the source code.
static_cast<float>(3) is exactly equivalent to (float)3 and will generate exactly the same code.
Given a float f = 42.0f reinterpret_cast<int*>(&f) is exactly equivalent to (int*)&f and will generate exactly the same code.
And so on. The only difference other than dynamic_cast , which, yes, can throw an exception. But this is because he does what C-style cannot do. Therefore, do not use dynamic_cast unless you need its functions.
It is usually safe to assume that compilers are intelligent. Given two different expressions that have the same semantics according to the standard, it is usually safe to assume that they will be implemented identically in the compiler.
Sorry . The second example should be reinterpret_cast, not dynamic_cast, of course. Corrected.
Well, just to make it absolutely clear, this is what the C ++ standard says:
Β§5.4.5:
Conversions Performed
- a
const_cast (5.2.11) - a
static_cast (5.2.9) - a
static_cast followed by const_cast - a
reinterpret_cast (5.2.10) or - a
reinterpret_cast followed by const_cast .
can be performed using an explicit type conversion notation. The same semantic restrictions and behavior. If the transformation can be interpreted in more than one of the methods listed above, the interpretation that appears first in the list is used, even if the cast as a result of this interpretation is poorly formed.
So, if something, since the C-style cast is implemented in terms of C ++ translations, the C-style should be slower. (Of course, this is not so, because the compiler generates the same code anyway, but it is more believable than a C ++-style cast slower.)
jalf Mar 23 '09 at 20:11 2009-03-23 ββ20:11
source share