Is there any advantage in using static_cast rather than C-style casting for non-pointer types?

后端 未结 2 1005
南旧
南旧 2021-02-11 15:10

I am well aware of the advantage in using static_cast rather than C-style casting for pointer types.

If the pointer types are incompatible, then:

相关标签:
2条回答
  • 2021-02-11 15:50

    I'm assuming that trivial uses of references to avoid pointers won't count.

    In that case: a C-style cast can be:

    • a const_cast
    • a static_cast
    • a static_cast followed by a const_cast,
    • a reinterpret_cast
    • a reinterpret_cast followed by a const_cast

    with the exception that static_cast's restrictions on inaccessible base classes are lifted.

    const_cast only applies to pointers and references.

    reinterpret_cast only applies to pointers and references. It does include pointer-to-integer conversions and vice versa, but that still involves a pointer type.

    That special exception for static_cast only applies to pointers and references.

    So yes, by excluding pointers and references, you've excluded everything that C-style casts support over a static_cast.

    If yes, is static_cast used for non-pointer types only in order to maintain coding consistency?

    Let's go with an analogy: I wouldn't use a chainsaw to open a bag of chips. I could, but chainsaws are dangerous, so by using one, I'd introduce unnecessary risks. It's very easy to use a chainsaw wrong, and if I do use it wrong, there's no safety mechanism to prevent accidents.

    0 讨论(0)
  • 2021-02-11 15:57

    One advantage which the other two answers didn't mention yet is that static_cast is much easier to spot. The meaning of parentheses is notoriously overloaded in C++ and it can be difficult to spot evil (or even incorrect) casts. When I see something ending in _cast though, it's like a mental speed bump: I slow down and carefully check why the type system is being subverted.

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