简体   繁体   English

C++ object model:调用虚拟 ZC1C425268E68385D1AB5074C17A94FptrZ4 导致崩溃

[英]C++ object model: calling virtual function by vptr leads to crash

I've got this code snippet, it tries to call virtual function through an object's vptr (pointing to virtual function table) and uses object pointer to convert to p->vptr, like this:我有这个代码片段,它试图通过对象的 vptr 调用虚拟 function(指向虚拟 function 表)并使用 ZA8CFDE6331BD59EB2AC96F8911C4B6ptr 66Z 指针转换为 p->v 指针

#include<iostream>
using namespace std;
struct C {
    virtual int f() {
        return 7;
    }
};
typedef int (*pf)();
int main() {
    C c1;
    pf *pvtable = (pf *) &c1;
    cout << (*pvtable[0])() << endl;
    return 0;
}

I used clang++14 to compile/link.我使用 clang++14 编译/链接。 On running it, programs returns 139, and no cout line is shown, seems it has crashed.运行它,程序返回 139,并且没有显示cout行,似乎它已经崩溃了。

Why it doesn't work and how to fix it?为什么它不起作用以及如何解决它?

Why it doesn't work为什么它不起作用

You are casting a pointer-to- C to a pointer-to- int(*)() .您正在将指向C的指针转换为指向int(*)()的指针。

This cast has no meaning in the C++ language and using the resulting pointer is explicitly Undefined Behavior.这种转换在 C++ 语言中没有任何意义,并且使用结果指针是明确的未定义行为。

and how to fix it?以及如何解决?

There is no reliable way.没有可靠的方法。

C++ does not promise the existence of a vtable pointer in any program, and if there is one C++ does not offer any method to access it. C++ 不 promise 在任何程序中都存在一个 vtable 指针,如果有一个 C++ 不提供任何访问它的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM