Checking whether a cross-cast could possibly work?

若如初见. 提交于 2019-11-30 07:15:48

It's not possible to detect this at compile-time. The class C that introduces the relationship could be found in a dynamically loadable library that hasn't even been written yet, and the compiler can't prove otherwise.

There may be a few exceptions though. If A has only private constructors (or a private destructor) then the compiler can be certain that there will be no new subclasses that aren't named as friends by A.

That's the whole meaning of the dynamic cast: It is dynamic i.e. it is checked at the runtime not at the compilation time.

The compiler only checks if the casted classes are polymorphic. If the classes are not polymorphic then there will not be enough information to check the casting at the runtime.

And finally after the dynamic cast the program should check if the received pointer is not null. If you cast to a reference then you should catch std::bad_cast.

Truth is when you use dynamic_cast you can cast any polymorphic type pointer to any polymorphic type pointer even when classes are unrelated to each other.

If you want compile-time check you need to use other casts - static_cast or implicit conversions - that might not suit for some other reasons in many cases.

The solution we use when dynamic_cast is needed is a templated function that does dynamic_cast and throws an exception if a null pointer is obtained. That's of course a runtime check only, but it's rather reliable.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!