Performance hit from C++ style casts?

前端 未结 7 774
半阙折子戏
半阙折子戏 2020-12-04 09:19

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 dead

7条回答
  •  有刺的猬
    2020-12-04 09:41

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

提交回复
热议问题