gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 18:28:43 25 4
gpt4 key购买 nike

我创建了一个简单的程序来演示我在使用多重继承的 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;
}

调用我的接口(interface)方法时,在 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.

知道问题出在哪里吗?

最佳答案

因为您使用的是多重继承,所以 vftable 指向预期为 MyInterface* 的指针实际上是指向 QGraphicsLineItem vftable.

dynamic_cast 会解决这个问题,因为它会返回正确的 vftable

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

一个简单的例子:

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)

关于c++ - 运行时检查失败 #0 - ESP 的值未在函数调用中正确保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8626160/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com