static_cast vs dynamic_cast

前端 未结 3 1950
死守一世寂寞
死守一世寂寞 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 18:14

    From MSDN -

    In general you use static_cast when you want to convert numeric data types such as enums to ints or ints to floats, and you are certain of the data types involved in the conversion. static_cast conversions are not as safe as dynamic_cast conversions, because static_cast does no run-time type check, while dynamic_cast does. A dynamic_cast to an ambiguous pointer will fail, while a static_cast returns as if nothing were wrong; this can be dangerous. Although dynamic_cast conversions are safer, dynamic_cast only works on pointers or references, and the run-time type check is an overhead.

    For more info, check out this link

提交回复
热议问题