转自https://stackoverflow.com/questions/8626160/run-time-check-failure-0-the-value-of-esp-was-not-properly-saved-across-a-fun。
自己编程时碰到这个问题,在这里完美解决,这里记录一下备忘。
Because you're using multiple inheritance, the vftable
pointer to what is expected to be a MyInterface*
is actually a pointer to a QGraphicsLineItem vftable
.
A dynamic_cast
would solve the issue because it will return the correct vftable
MyInterface* mInterface = dynamic_cast<MyInterface*>(item);
A simple example:
class A
{
public:
virtual void foo() = 0;
};
class B
{
public:
virtual void goo() {};
};
class C : public B, public A
{
public:
virtual void foo() {};
};
//....
B* c = new C; // c is at 0x00a97c78
A* a = (A*)c; // a is at 0x00a97c78 (vftable pointer of B)
A* a1 = dynamic_cast<A*>(c); // a1 is at 0x00a97c7c (vftable pointer of A)
文章的意思是说,当类继承自多个父类时,如果用强制类型转换,那么转换后的类的虚函数表指针实际上指向的是第一个父类,当调用第二个父类的函数时,就会出现运行时异常。而用dynamic_cast进行函数类型转换,虚函数表指针可以指向实际的父类空间的地址。