当 class 有一些虚拟方法时,它的所有方法都使用 vtable 吗?

When a class has some virtual methods, do all it's methods use a vtable?

在下面的这个例子中,Type 有一个虚拟方法,所以它有一个 vtable。但是,Type::Bar() 不是虚拟的。调用 Bar() 时,调用是否也通过 vtable 机制,还是仅适用于 Foo()?

struct Base {
  virtual void Foo() {}
}

struct Type : Base {
  void Foo() override {}
  void Bar() {}
}

Base* b = new Type();
Type* t = static_cast<Type*>(b);
t->Bar(); // Does this use a vtable?

However, Type::Bar() is not virtual. When calling Bar(), does the call also go through the vtable mechanism, or will it only apply to Foo()?

virtual函数调用的函数在编译时决定。因此,没有充分的理由让实现选择 vtable 来分派对非 virtual 函数的调用。但是,即使对于非 virtual 函数,该标准也不禁止实现使用 vtable

@EJP 说得更好:

该标准不要求实现将 vtable 用于虚函数。这是一个实现细节。使用 vtables 的理智实现不会通过包含非虚拟函数

在其中浪费 space

vtable 的概念是 c++ 标准中未进一步提及的实现细节。

但是如果在 class 处提供了非虚函数,当然没有必要在那里包含它们,但在编译时完全绑定调用