虚拟表在内存中的布局?
虚拟表如何存储在内存中?他们的布局?
例如,
class A{
public:
virtual void doSomeWork();
};
class B : public A{
public:
virtual void doSomeWork();
};
A类和B类的虚拟表在内存中的布局如何?
how are virtual tables stored in memory? their layout?
e.g.
class A{
public:
virtual void doSomeWork();
};
class B : public A{
public:
virtual void doSomeWork();
};
How will be the layout of virtual tables of class A and class B in memory?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
对于 Linux 中的 GCC 编译器,运行:
输出是:
我还创建了 vtable-dumper 工具来列出虚拟表的内容在共享对象中。使用此工具,您不需要编译标头,只需在对象上运行它:
For GCC compiler in Linux run:
The output is:
Also I've created the vtable-dumper tool to list contents of virtual tables in the shared objects. With this tool you don't need to compile headers, just run it on the object:
正如其他人所说,这取决于编译器,而不是您在日常使用 C++ 时真正需要考虑的事情。但是,如果您只是对这个问题感到好奇,您应该阅读 Stan Lippman 的书 C++ 对象模型内部。
As others have said, this is compiler dependant, and not something that you ever really need to think about in day-to-day use of C++. However, if you are simply curious about the issue, you should read Stan Lippman's book Inside the C++ Object Model.
内存中的 vtable 布局完全依赖于编译器;没有采取“正确”或通用的方法。
vtable layout in memory is completely compiler dependent; there's no "correct" or universal approach taken.
正如其他人已经写过的那样,没有通用的方法。 (哎呀,甚至没有人强制要求使用虚拟表。)
但是,我相信它们很可能被实现为引用函数指针表的对象中某个偏移处的隐藏指针。某些虚拟函数的地址占用该表中的某些偏移量。通常还有一个指向动态类型的
std::type_info
对象的指针。如果您对此类内容感兴趣,请阅读 Lippmann 的“C++ 对象模型内部”< /a>.然而,除非您的兴趣是学术性的(或者您正在尝试编写一个 C++ 编译器——但您不需要询问),否则您不应该打扰。这是您不需要了解也不应该依赖的实现细节。
As others already wrote, there is no general approach. (Heck, nobody even mandates that virtual tables are used at all.)
However, I believe they are most likely implemented as a hidden pointer at a certain offset in the object which references a table of function pointers. Certain virtual functions' addresses occupy certain offsets in that table. Usually there's also a pointer to the dynamic type's
std::type_info
object.If you're interested in things like this, read Lippmann's "Inside the C++ Object Model". However, unless your interest is academic (or you're trying to write a C++ compiler -- but then you shouldn't need to ask), you shouldn't bother. It's an implementation detail you don't need to know and should never rely on.
来自 维基百科:
所以答案是否定的。 vtable 的布局是实现定义的。
From wikipedia:
So the answer is no. Layout of vtable is implementation defined.
有关 Open Watcom 类布局的详细说明,请查看 类布局笔记
For a very detailed description of Open Watcom's class layout have a look at the Class Layout notes