dynamic_cast on llvm clang compiler failing

2019-06-18 04:42发布

问题:

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));