static_cast(foo) vs. (int)foo

前端 未结 3 1391
粉色の甜心
粉色の甜心 2021-02-01 05:02

Could somebody please elaborate on the differences?

3条回答
  •  既然无缘
    2021-02-01 05:46

    Look at what Stroustrup has to say about that, including the following:

    Because the C-style cast (T) can be used to express many logically different operations, the compiler has only the barest chance to catch misuses. [...]

    The "new-style casts" were introduced to give programmers a chance to state their intentions more clearly and for the compiler to catch more errors. [...]

    In particular, C++ makes the distinction between static_cast and reinterpret_cast:

    The idea is that conversions allowed by static_cast are somewhat less likely to lead to errors than those that require reinterpret_cast. In principle, it is possible to use the result of a static_cast without casting it back to its original type, whereas you should always cast the result of a reinterpret_cast back to its original type before using it to ensure portability.

提交回复
热议问题