虚函数调用的编译器优化 [英] Compiler Optimization of virtual function calls

查看:71
本文介绍了虚函数调用的编译器优化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最流行的示例说明了为什么在运行时进行虚拟调度是在编译时无法确定要创建哪个派生类的情况.例如:

Most popular example to illustrate why virtual dispatch happens at runtime is when it cannot be determined at compile time which Derived class is going to be created. For example:

Base* b = (rand() % 2 == 1 ? new Derived1() : new Derived2());

或何时取决于用户输入.

or when it depends on user input.

假设情况并非如此,并且可以在编译时完全确定基本指针所指向的派生类.

Suppose none of that is the case and it can be completely determined at compile time which Derived class the base pointer is referring to.

如果在编译时知道基类指针指向哪个Derived类,编译器是否通过将虚拟函数调用替换为适当的Derived函数并在运行时不执行vtable查找来优化虚拟函数调用?

If it is known at compile time which Derived class the base class pointer points to, does the compiler optimize the virtual function call by substituting it with appropriate Derived function and not doing vtable lookup during runtime?

推荐答案

这种优化称为Devirtualization.至少Clang执行了此操作,请参见此博客文章此帖子在邮件列表中.

Such optimization is called Devirtualization. At least Clang performs it, see this blog post and this post on mailing list.

这篇关于虚函数调用的编译器优化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆