运行时检查失败#0 - ESP的值未在函数调用中正确保存

时间:2011-12-24 18:22:09

标签: c++ visual-studio qt multiple-inheritance qgraphicsitem

我创建了一个简单的程序,演示了我使用多重继承的Qt应用程序时遇到的运行时错误。继承树看起来像:

QGraphicsItem (abstract)
      \
     QGraphicsLineItem      MyInterface (abstract)
                 \          /
                  \        /
                  MySubclass

以下是代码:

/* main.cpp */
#include <QApplication>
#include <QGraphicsScene>
#include <QGraphicsLineItem>

//simple interface with one pure virtual method
class MyInterface
{
public:
  virtual void myVirtualMethod() = 0;
};

//Multiple inheritance subclass, simply overrides the interface method
class MySubclass: public QGraphicsLineItem, public MyInterface
{
public:
  virtual void myVirtualMethod() { }
};

int main(int argc, char** argv)
{
  QApplication app(argc, argv); //init QApplication
  QGraphicsScene *scene = new QGraphicsScene(); //create scene

  scene->addItem(new MySubclass()); // add my subclass to the scene

  Q_FOREACH(QGraphicsItem *item, scene->items()) // should only have one item
  {
    MyInterface *mInterface = (MyInterface*)item; // cast as MyInterface
    mInterface->myVirtualMethod(); // <-- this causes the error
  }
  return 0;
}

调用我的接口方法时,Visual Studio中的调试会导致运行时错误:

    Run-Time Check Failure #0 - The value of ESP was not properly 
    saved across a function call.  This is usually a result of 
    calling a function declared with one calling convention with 
    a function pointer declared with a different calling convention.

知道问题是什么吗?

2 个答案:

答案 0 :(得分:8)

因为您正在使用多重继承,所以指向vftable的{​​{1}}指针实际上是指向MyInterface*的指针。

QGraphicsLineItem vftable可以解决问题,因为它会返回正确的dynamic_cast

vftable

一个简单的例子:

MyInterface* mInterface = dynamic_cast<MyInterface*>(item);

答案 1 :(得分:1)

如果您使用动态广告

,则会解决您的问题
MyInterface* mInterface = dynamic_cast<MyInterface*>(item);

This questions处理各种C ++强制转换以及何时使用它们。在您的情况下,由于多重继承,您应该使用动态强制转换