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

前端 未结 9 1882
滥情空心
滥情空心 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:52

    In short:

    1. static_cast<>() gives you a compile time checking ability, C-Style cast doesn't.
    2. static_cast<>() can be spotted easily anywhere inside a C++ source code; in contrast, C_Style cast is harder to spot.
    3. Intentions are conveyed much better using C++ casts.

    More Explanation:

    The static cast performs conversions between compatible types. It is similar to the C-style cast, but is more restrictive. For example, the C-style cast would allow an integer pointer to point to a char.

    char c = 10;       // 1 byte
    int *p = (int*)&c; // 4 bytes
    

    Since this results in a 4-byte pointer pointing to 1 byte of allocated memory, writing to this pointer will either cause a run-time error or will overwrite some adjacent memory.

    *p = 5; // run-time error: stack corruption
    

    In contrast to the C-style cast, the static cast will allow the compiler to check that the pointer and pointee data types are compatible, which allows the programmer to catch this incorrect pointer assignment during compilation.

    int *q = static_cast(&c); // compile-time error
    

    Read more on:
    What is the difference between static_cast<> and C style casting
    and
    Regular cast vs. static_cast vs. dynamic_cast

提交回复
热议问题