问题描述
虚拟类的每个对象都有一个指向vtable的指针?
Does every object of virtual class have a pointer to vtable?
或者只有带有虚函数的基类的对象有它吗?
Or only the object of base class with virtual function has it?
vtable存储在哪里?所有具有虚拟方法的类将具有一个由所有对象共享的vtable,它们的代码部分或数据部分。
Where did the vtable stored? code section or data section of process?
推荐答案
每个对象实例都将有一个指向该vtable的指针(这是vtable的发现方式),通常称为vptr。编译器隐式生成代码以初始化构造函数中的vptr。
Each object instance will have a pointer to that vtable (that's how the vtable is found), typically called a vptr. The compiler implicitly generates code to initialize the vptr in the constructor.
注意,这些都不是由C ++语言强制的 - 一个实现可以处理虚拟分派一些其他方式if它想要。但是,这是我熟悉的每个编译器使用的实现。 Stan Lippman的书内在C ++对象模型描述了这是如何工作非常好。
Note that none of this is mandated by the C++ language - an implementation can handle virtual dispatch some other way if it wants. However, this is the implementation that is used by every compiler I'm familiar with. Stan Lippman's book, "Inside the C++ Object Model" describes how this works very nicely.
这篇关于虚拟类的每个对象都有一个指向vtable的指针吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!