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

后端 未结 2 1008
南旧
南旧 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.

提交回复
热议问题