What does a const cast do differently?

前端 未结 6 1488
心在旅途
心在旅途 2020-12-21 06:40

Is there an actual difference between a const_cast and c style cast (ObjectType) ?

相关标签:
6条回答
  • 2020-12-21 06:51

    A const_cast can only add or remove const-ness (or volatile-ness, though this is much less common).

    A C-style cast can do the same as any of the "new" casts, except for a dynamic_cast (and it can do a few things none of them can do, though it's not really relevant here).

    0 讨论(0)
  • 2020-12-21 06:52

    A const_cast is more restricted and won't let you do anything other than change const-ness. That makes it safer i.e. less accident-prone.

    In addition it's easier to search for.

    0 讨论(0)
  • 2020-12-21 06:57

    C-style cast in C++ attempts a static cast, a reinterpret cast, a const cast, or a combination of those.

    It is recommended to avoid C casts mainly because...

    • reinterpret casts and const casts are used seldomly enough that it's good to emphasize what you're doing,
    • in other cases, when you want a static cast, writing it explicitly gives you additional compile-time checks compared to C casts.
    0 讨论(0)
  • 2020-12-21 07:02

    Same action. A C-style cast can cast away the const all the same.

    The reason for const_cast is that it can serve as a searchable red flag, something to search for and carefully review/punish the guilty. The idea is that C++ is much more type-tight that C. So deliberate violations of the type system (such as violating const correctness), if not impossible, are easy to spot.

    Making such violations of the type safety completely impossible would break too much backwards compatibility.

    0 讨论(0)
  • 2020-12-21 07:05

    const_cast can modify only the const-ness (or volatile-ness) of the argument, not it's basic type. So

     const T *tc = f();
     volatile T *tv = g();
    
     U *ua = const_cast<U*>(tc); //error
     U *ub = const_cast<U*>(tv); //error
    
     U *ub = (U*)(tc); //okay
     U *ub = (U*)(tv); //okay
    

    So c-style cast modifies cv-qualified T* to U* without any problem.

    0 讨论(0)
  • 2020-12-21 07:07

    A const_cast conveys specific information about the intent behind the cast that a C cast cannot.

    If you accidentally try to use a const_cast for purposes other than adding or removing const or volatile, the compiler will help you with an error message.

    Also, const_cast is searchable, unlike a C-style cast.

    0 讨论(0)
提交回复
热议问题