tags:

views:

1886

answers:

6

I am new to C++ style casts and I am worried that using C++ style casts will ruin the performance of my application because I have a real-time-critical deadline in my interrupt-service-routine.

I heard that some casts will even throw exceptions!

I would like to use the C++ style casts because it would make my code more "robust". However, if there is any performance hit then I will probably not use C++ style casts and will instead spend more time testing the code that uses C-style casts.


Has anyone done any rigorous testing/profiling to compare the performance of C++ style casts to C style casts?

What were your results?

What conclusions did you draw?

+31  A: 

The only one with any extra cost at runtime is dynamic_cast, which has capabilities that cannot be reproduced directly with a C style cast anyway. So you have no problem.

The easiest way to reassure yourself of this is to instruct your compiler to generate assembler output, and examine the code it generates. For example, in any sanely implemented compiler, reinterpret_cast will disappear altogether, because it just means "go blindly ahead and pretend the data is of this type".

Daniel Earwicker
+35  A: 

If the C++ style cast can be conceptualy replaced by a C-style cast there will be no overhead. If it can't, as in the case of dynamic_cast, for which there is no C equivalent, you have to pay the cost one way or another.

As an example, the following code:

int x;
float f = 123.456;

x = (int) f;
x = static_cast<int>(f);

generates identical code for both casts with VC++ - code is:

00401041   fld         dword ptr [ebp-8]
00401044   call        __ftol (0040110c)
00401049   mov         dword ptr [ebp-4],eax

The only C++ cast that can throw is dynamic_cast when casting to a reference. To avoid this, cast to a pointer, which will return 0 if the cast fails.

anon
Come on, Trevor, this answer is surely THE answer?!
Daniel Earwicker
A C++ style cast is never replaced by a C-style cast. If anything, it's the other way around. The standard only specifies the behavior of the C++-style casts. The C-style ones are described in terms of the C++ ones.
jalf
@jalf yes - I meant replaced conceptualy
anon
Yeah, but might be worth making it 110% clear, if the OP is going to accept it. ;)
jalf
But the assembler listing... the ASSEMBLER LISTING!!! What does he want, *blood*? :)
Daniel Earwicker
Do you need to ask? :p
jalf
+2  A: 

When using dynamic_cast several checks are made during runtime to prevent you from doing something stupid (more at the GCC mailing list), the cost of one dynamic_cast depends on how many classes are affected, what classes are affected, etc.
If you're really sure the cast is safe, you can still use reinterpret_cast.

tstenner
If you find you need to use reinterpret_cast, you are definitely venturing into "implementation specific" territory, and possibly "undefined behaviour" land too
anon
Please note that reinterpret_cast may be subject to different aliasing rules than static_cast etc.
leander
+10  A: 

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.)

jalf
Given your comment of: "it is usually safe to assume that they will be implemented identically in the compiler". Do you or have you done any embedded work or real-time-critical work?
Trevor Boyd Smith
dynamic_cast will only throw when operating on references. If it is working on a pointer, it will return 0 if the cast fails. And why on earth would you use dynamic_cast on a float* to int* conversion? That makes no sense.
Brian Neal
oh oops, I meant reinterpret_cast, of course. It's fixed now. Thanks for pointing it out. :)
jalf
+1. haha 5.4.5 was the first that came to mind when i read that question :D
Johannes Schaub - litb
@litb - not sure whether to be impressed or frightened.
Daniel Earwicker
Oh jeez, don't tell me you could *remember* that it was 5.4.5... I had to look it up! ;)
jalf
haha, nono don't be afraid. i just knew C style casts are defined in terms of C++ style ones :p i got no love for remembering section numbers like that :)
Johannes Schaub - litb
@litb: by the way, I don't suppose you could cast some light on http://tinyurl.com/c9daz8 ? ;)
jalf
+1  A: 

Although I agree with the statement "the only one with any extra cost at runtime is dynamic_cast", keep in mind there may be compiler-specific differences.

I've seen a few bugs filed against my current compiler where the code generation or optimization was slightly different depending on whether you use a C-style vs. C++-style static_cast cast.

So if you're worried, check the disassembly on hotspots. Otherwise just avoid dynamic casts when you don't need them. (If you turn off RTTI, you can't use dynamic_cast anyway.)

leander
I'd be interested to see an example of the use of dynamic_cast when you don't need it.
anon
An example could be if you downcast to a derived class (so you'd often use dynamic_cast), but you already know that the cast is legal, so you can use static_cast instead.
jalf
@Neil: I guess I meant more along the lines of "refactor to avoid dynamic_cast". I look pretty hard at the consequences before I start sticking "virtual" in inheritance hierarchies, because I *know* I'm making a tradeoff, and sometimes choosing a different design pattern can solve the problem...
leander
@Neil: if you're _sure_ it's a safe downcast and there's no virtual inheritance, you can use static_cast instead. Also, I believe you _can_ use dynamic_cast for upcasts, but that'd generally be silly (perhaps excepting virtual inheritance?). Treading into less-known territory here...
leander
"I've seen a few bugs filed against my current compiler where the code generation or optimization was slightly different depending on whether you use a c-style vs. c++-style static_cast cast.": I wonder if the C-style cast was doing more than one thing (const_cast *and* static_cast, f.e.).
Max Lybbert
+2  A: 

There are four C++ style casts:

  • const_cast
  • static_cast
  • reinterpret_cast
  • dynamic_cast

As already mentioned, the first three are compile-time operations. There is no run-time penalty for using them. They are messages to the compiler that data that has been declared one way needs to be accessed a different way. "I said this was an int*, but let me access it as if it were a char* pointing to sizeof(int) chars" or "I said this data was read-only, but now I want to modify it."

Aside from data corruption by casting to the wrong type and trouncing over data (always a possibility with C-style casts) the most common run-time problem with these casts is data that actually is declared const may not be castable to non-const, and doing so is undefined. You'll likely get a crash on an OS, but might not get even that in an embedded system.

dynamic_cast is a run-time construct, so it has to have a run-time cost.

The value of these casts is that they specifically say what you're trying to cast from/to, stick out visually, and can be searched for with brain-dead tools. I would recommend using them over using C-style casts.

Max Lybbert