Why would there be a performance hit? They perform exactly the same functionality as C casts. The only difference is that they catch more errors at compile-time, and they're easier to search for in your 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 cast that differs is dynamic_cast
, which, yes, can throw an exception. But that is because it does things that the C-style cast cannot do. So don't use dynamic_cast
unless you need its functionality.
It is usually safe to assume that compiler writers 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.
Oops: The second example should be reinterpret_cast, not dynamic_cast, of course. Fixed it now.
Ok, just to make it absolutely clear, here is what the C++ standard says:
§5.4.5:
The conversions performed by
- a
const_cast
(5.2.11)
- a
static_cast
(5.2.9)
- a
static_cast
followed by a const_cast
- a
reinterpret_cast
(5.2.10), or
- a
reinterpret_cast
followed by a const_cast
.
can be performed using the cast
notation of explicit type conversion.
The same semantic restrictions and
behaviors apply. If a conversion can
be interpreted in more than one of the
ways listed above, the interpretation
that appears first in the list is
used, even if a cast resulting from
that interpretation is ill-formed.
So if anything, since the C-style cast is implemented in terms of the C++ casts, C-style casts should be slower. (of course they aren't, because the compiler generates the same code in any case, but it's more plausible than the C++-style casts being slower.)