问题描述
我知道虚函数本质上是一个vtable包含的函数指针,这使得多边形调用因为间接等等更慢。
但是我想知道当调用是确定性的时候编译器优化。
按确定性,我的意思是以下情况:
I know that virtual functions are essentially function pointers contained on a vtable, which makes polymorphic calls slower because of indirection etc.But I'm wondering about compiler optimisation when call is deterministic.By deterministic, I mean the following cases:
- 对象是一个值而不是引用,因此没有多态可能:
struct Foo
{
virtual void DoSomething(){....}
};
int main()
{
Foo myfoo;
myfoo.DoSemthing();
return 0;
}
- 无子类:
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()
。
In the first case, this will not be a virtual call. The compiler will issue a call straight to Foo::DoSomething()
.
在第二种情况下,复杂。一个,它是最好的链接时间优化,因为对于一个特定的翻译单元,编译器不知道谁可能继承该类。你得到的另一个问题是共享库,这也可能继承而不是你的可执行程序知道任何关于它。
In the second case, it's more complicated. For one, it's at-best a link time optimization, since for a specific translation unit, the compiler doesn't know who else might inherit from that class. The other problem you get is with shared libraries which might also inherit without your executable knowing anything about it.
一般来说,这是一个编译器优化称为虚拟函数调用消除 或偏虚拟化,并且是一个活跃的研究领域。
In general, though, this a compiler optimization known as virtual function call elimination, or devirtualization, and is somewhat of an active field of research. Some compilers do it to some extent, others don't do it at all.
请参阅GCC(g ++), -fdevirtualize
和 -fdevirtualize-speculatively
。在质量保证水平的提示的名称。
See, in GCC (g++), -fdevirtualize
and -fdevirtualize-speculatively
. The names kind of hint at the guaranteed level of quality.
这篇关于虚函数开销当确定性(c ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!