鉴于:
例子.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;
};
例子.cpp
#include "Example.h"
void Derived::accept(struct DerivedVisitor* v) {
v->visit(this);
}
假设我想从“scratch”创建一个Derived的实例。由于它包含一个虚函数,来自Base,我将如何获取其虚函数表的地址,以便我可以执行以下操作:
主文件
#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。