Performance hit from C++ style casts?

前端 未结 7 815
半阙折子戏
半阙折子戏 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:43

    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, and now I need to pass it to a function that won't modify it, but doesn't take the parameter as a const reference."

    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. Casting something declared const to non-const and then modifying it is undefined. Undefined means you're not even guaranteed to get a crash.

    dynamic_cast is a run-time construct and 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.

提交回复
热议问题