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

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

    The question is bigger than just using wither static_cast or C style casting because there are different things that happen when using C style casts. The C++ casting operators are intended to make these operations more explicit.

    On the surface static_cast and C style casts appear to the same thing, for example when casting one value to another:

    int i;
    double d = (double)i;                  //C-style cast
    double d2 = static_cast( i );  //C++ cast
    

    Both of these cast the integer value to a double. However when working with pointers things get more complicated. some examples:

    class A {};
    class B : public A {};
    
    A* a = new B;
    B* b = (B*)a;                                  //(1) what is this supposed to do?
    
    char* c = (char*)new int( 5 );                 //(2) that weird?
    char* c1 = static_cast( new int( 5 ) ); //(3) compile time error
    

    In this example (1) maybe OK because the object pointed to by A is really an instance of B. But what if you don't know at that point in code what a actually points to? (2) maybe perfectly legal(you only want to look at one byte of the integer), but it could also be a mistake in which case an error would be nice, like (3). The C++ casting operators are intended to expose these issues in the code by providing compile-time or run-time errors when possible.

    So, for strict "value casting" you can use static_cast. If you want run-time polymorphic casting of pointers use dynamic_cast. If you really want to forget about types, you can use reintrepret_cast. And to just throw const out the window there is const_cast.

    They just make the code more explicit so that it looks like you know what you were doing.

提交回复
热议问题