static_cast vs dynamic_cast

前端 未结 3 1955
死守一世寂寞
死守一世寂寞 2021-02-05 17:43

Suppose I\'m given a C++ library full of inheritance. I\'m given a Base* in a function when I know that it is actually pointing to a Derived object and

3条回答
  •  粉色の甜心
    2021-02-05 17:56

    When in doubt, you should prefer dynamic_cast. It might be slower, but you probably won't notice the difference anyway.

    If you need speed, use the following snippet:

    template 
    Derived safe_static_cast(Base b)
    {
      assert((void*)dynamic_cast(b) && "safe_static_cast failed!");
      return static_cast(b);
    }
    

    Or something equivalent.

    The idea is that in debug builds, it checks that it's indeed what you thought it would be, and it release builds... well everything has already been tested, hasn't it ?

提交回复
热议问题