Why use static_cast(x) instead of (int)x?

前端 未结 9 1885
滥情空心
滥情空心 2020-11-22 02:38

I\'ve heard that the static_cast function should be preferred to C-style or simple function-style casting. Is this true? Why?

9条回答
  •  一整个雨季
    2020-11-22 02:54

    It's about how much type-safety you want to impose.

    When you write (bar) foo (which is equivalent to reinterpret_cast foo if you haven't provided a type conversion operator) you are telling the compiler to ignore type safety, and just do as it's told.

    When you write static_cast foo you are asking the compiler to at least check that the type conversion makes sense and, for integral types, to insert some conversion code.


    EDIT 2014-02-26

    I wrote this answer more than 5 years ago, and I got it wrong. (See comments.) But it still gets upvotes!

提交回复
热议问题