[英]C++ How do i get a pointer to a class' virtual function table?
Given:鉴于:
Example.h例子.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例子.cpp
#include "Example.h"
void Derived::accept(struct DerivedVisitor* v) {
v->visit(this);
}
Say that I wanted to create an instance of Derived from "scratch".假设我想从“scratch”创建一个Derived的实例。 As it contains a virtual function, from Base , how would i get a hold of the address to its virtual function table so that i could do something like this:
由于它包含来自Base的虚拟 function,我将如何获取其虚拟 function 表的地址,以便我可以执行以下操作:
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;
}
Is this compiler specific?这个编译器是特定的吗? If so, I am using MinGW if anyone is familiar with it.
如果是这样,如果有人熟悉它,我正在使用 MinGW。
Is this compiler specific?
这个编译器是特定的吗?
Yes, this is compiler specific.是的,这是特定于编译器的。
There is no such thing as a "virtual function table" in the C++ language. C++ 语言中没有“虚拟 function 表”之类的东西。 Such table is an implementation detail.
这样的表是一个实现细节。
Given that such table doesn't exist in the language, there is also no way to get a pointer to the table in standard C++.鉴于该语言中不存在此类表,因此也无法在标准 C++ 中获取指向该表的指针。 Assuming your compiler has such thing as a virtual table (which is a reasonable assumption), then it may be possible that your compiler documents a way to access it.
假设您的编译器具有虚拟表之类的东西(这是一个合理的假设),那么您的编译器可能会记录一种访问它的方法。 I doubt that however.
然而,我对此表示怀疑。 You may have to do that in assembly language.
你可能必须用汇编语言来做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.