【发布时间】:2016-02-10 17:31:14
【问题描述】:
我知道虚函数本质上是包含在 vtable 中的函数指针,由于间接等原因,这使得多态调用变慢。 但是我想知道调用是确定性时的编译器优化。 确定性是指以下情况:
- 对象是值而非引用,因此不可能存在多态性:
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;
}
【问题讨论】:
-
值没有多态性,因此我不太明白你的意思 a)。
-
Foo* a = new Foo()和Foo* b = new Foo()没有区别。你想在这里说明什么? -
这些都是潜在可优化的,因为
a、b和c的动态类型在编译时都是已知的。编译器是否真正执行优化是另一回事。正如 Yam Marcovic 所说,这是一个活跃的研究领域,因此最先进的技术在不断变化。 -
您想知道编译器优化,但我想知道您的问题是什么以及您自己做了什么来回答它......
标签: c++ polymorphism