简体   繁体   English

在静态分配的对象上调用虚拟函数时是否使用虚拟表

[英]Is virtual table used when calling virtual functions on statically allocated objects

Here's an example: 这是一个例子:

struct A {
  virtual int f() const { return 1; }
};

struct B : A {
  virtual int f() const { return 2; }
};

int main() {
  B b;
  cout << b.f() << endl;
}

Is there going to be a virtual table lookup incurred to call f() on the instance of B , or not? 是否需要在B的实例上调用f()进行虚拟表查找? Or is it possible, but compilers can optimize it out? 还是有可能,但是编译器可以对其进行优化?

Depends on the compiler and optimization options. 取决于编译器和优化选项。

But as a rule, when a modern compiler knows the most derived type of an object, it will optimize away (the indirection of) direct virtual calls on the objects. 但是通常,当现代编译器知道对象的最派生类型时,它将优化对对象的直接虚拟调用(的间接调用)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM