C++ 如何获取指向 class' 虚函数 table 的指针?

C++ How do i get a pointer to a class' virtual function table?

鉴于:

Example.h

struct Base {
    virtual ~Def() = default;

    virtual void accept(struct DerivedVisitor* v) = 0;
};

struct Derived : Base {
    int num;
    void accept(struct DerivedVisitor* v) override;
};

struct DerivedVisitor {
    virtual void visit(Derived* d) = 0;
};

Example.cpp

#include "Example.h"

void Derived::accept(struct DerivedVisitor* v) {
    v->visit(this);
}

说我想从“scratch”创建一个 Derived 的实例。因为它包含一个虚函数,来自 Base,我如何获得它的虚函数 table 的地址,以便我可以做这样的事情:

main.cpp

#include <iostream>
#include <memory>
#include "Example.h"

struct Visitor : DerivedVisitor {
    void visit(Derived* d) override {
        std::cout << d->num << std::endl;
    }
};

int main() {
    int num = 5;
    
    // Create Derived instance from scratch
    auto der = malloc(sizeof(Derived));
    auto derBytes = static_cast<char*>(der);
    new (derBytes) void*(/*HERE I NEED POINTER TO Derived VFT*/); // <------------- How?
    new (derBytes + sizeof(Base)) int(num);

    // Just to see that it works:
    Base* base = reinterpret_cast<Derived*>(der);
    Visitor visitor{};
    base->accept(&visitor);

    free(der);
    return 0;
}

这个编译器是特定的吗?如果是这样,如果有人熟悉的话,我正在使用 MinGW。

Is this compiler specific?

是的,这是特定于编译器的。

C++ 语言中没有“虚函数table”这样的东西。这样table是一个实现细节。

鉴于语言中不存在这样的 table,因此在标准 C++ 中也无法获得指向 table 的指针。假设您的编译器具有虚拟 table 之类的东西(这是一个合理的假设),那么您的编译器可能会记录一种访问它的方法。但是我对此表示怀疑。您可能必须使用汇编语言来完成此操作。