dynamic_cast on llvm clang compiler failing

折月煮酒 提交于 2019-12-08 17:47:10

问题


I am seeing a strange failure where the dynamic_cast is returning NULL on clang compiler. But the same code is working with gcc environment.

Could you please point me what might be the root cause? What might the difference between the dynamic_cast on llvm and gcc.

I am using the default behavior of both the compiler where i think the RTTI is enable by default.

template<typename T> T* 
find_msg_of_type(
    MsgList *list
) {
    T* msg = NULL;

    if (list) {
        for (std::vector<MsgList*>::iterator it = list->element.begin();
                                                        it != list->element.end();
                                                        it++) {// MsgList can be list of objects build with GSoap.
            if (typeid(*(*it)) == typeid(T)) {
                msg = dynamic_cast<T*>(*it); // Failing on clang but this same code is working with gcc compiler.
                break;
            }
        }
    }

    return msg;
}

One more observation: With gcc

if (typeid(*(*it)) == typeid(T))

is working perfectly as expected but with clang

if (typeid(*(*it)) == typeid(T))

comparison is showing different behavior.. not sure exactly why this differs.

Thanks


回答1:


For code like this, a Good Idea is to statically ensure that the class T is derived from MsgList. Using boost, this can be done thusly:

BOOST_STATIC_ASSERT((boost::is_base_and_derived::value));



来源:https://stackoverflow.com/questions/14119136/dynamic-cast-on-llvm-clang-compiler-failing

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