gpt4 book ai didi

c++ - 确定性时的虚函数开销 (c++)

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:01:29 27 4
gpt4 key购买 nike

我知道虚函数本质上是包含在 vtable 中的函数指针,由于间接等原因,这会使多态调用变慢。但是我想知道调用是确定性的时编译器优化。我所说的确定性是指以下情况:

  1. 该对象是一个值而不是一个引用,因此不可能存在多态性:
struct Foo
{
virtual void DoSomething(){....}
};

int main()
{
Foo myfoo;
myfoo.DoSemthing();
return 0;
}
  1. 引用的是一个没有 child 的类(class):
struct Foo
{
virtual void DoSomething();
};
struct Bar : public Foo
{
virtual void DoSomething();
};

int main()
{
Foo* a = new Foo();
a->DoSomething(); //Overhead ? a doesn't seem to be able to change nature.

Foo* b = new Bar();
b->DoSomething(); //Overhead ? It's a polymorphic call, but b's nature is deterministic.

Bar* c = new Bar();
c->DoSomething(); //Overhead ? It is NOT possible to have an other version of the method than Bar::DoSomething
return 0;
}

最佳答案

在第一种情况下,这不是虚拟调用。编译器将直接调用 Foo::DoSomething()

第二种情况比较复杂。其一,它至多是链接时间优化,因为对于特定的翻译单元,编译器不知道还有谁可能继承自该类。您遇到的另一个问题是共享库,它们也可能在您的可执行文件对其一无所知的情况下继承。

不过,总的来说,这是一种称为虚拟函数调用消除去虚拟化的编译器优化,并且在某种程度上是一个活跃的研究领域。一些编译器在某种程度上做到了这一点,而另一些则根本不这样做。

参见,在 GCC (g++) 中,-fdevirtualize-fdevirtualize-speculatively。这些名称暗示了质量的保证水平。

关于c++ - 确定性时的虚函数开销 (c++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35322010/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com