I have encountered a strange error relating to template class in C++. The codes run OK most of the time, but in one occasion it failed. The following is simplified codes:
template <class T>
class Class1
{
...
T *func();
...
};
// ---------------------------------------------------------------
template <class T>
T *Class1<T>::func(...)
{
...
string name = typeid(T).name();
T *ptr = a_queue.front(); // a_queue is of type "queue<T *>"
ptr->some_func(); // failed
...
}
// ---------------------------------------------------------------
Class1<Class2> class1;
class1.func();
Suppose Class1 is specialized with T is Class2 and Class3 respectively. In Class1<Class2>::func, ptr is declared as Class3 pointer in that occasion! So the type is not safe in template class?
Any idea? Thanks!
Edit:
I have added string name = typeid(T).name(), then T will be correct type (Class2), but when call the member function some_func of Class2, there is a error:
cannot access memory address at 0x10
[Solved] Final edit 2011/11/09:
I have found the problem, it is not related to template class, but caused by deleting the wrong pointer, which is not newed in the same function with delete and has been pushed into the queue!
That is equivalent to a NULL pointer reference. The compiler started with some
T *ptr = 0and tried to find a member (or vtable) ofTat offset 0x10 so it looked at memory0 + 0x10. So I don’t think your problem is a matter of template types but ofa_queue.front()containing NULL.