虚函数调用和非虚函数调用之间的区别? [英] Difference between calling of virtual function and non virtual function?

查看:237
本文介绍了虚函数调用和非虚函数调用之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这实际上是一个面试问题,我不能弄清楚答案。任何人都知道这一点?

This is in fact an interview question, I can't figure out the answer. Anyone knows about this? You can talk about any difference, for example, the data that are push into stack.

推荐答案

虽然虚拟主义/动态分派是严格实现定义的,大多数(读取所有已知)编译器通过使用 vptr vtable

Though virtualism/dynamic dispatch is strictly implementation defined, most(read all known) compilers implement it by using vptr and vtable.

说到这里,调用非虚函数和虚函数之间的区别是:

Having said that, the difference between calling a non virtual function and virtual function is:

非虚函数在编译时下解析静态,而虚函数解析 c

Non-virtual functions are resolved statically at Compile-time, While Virtual functions are resolved dynamically at Run-time.

为了实现这种灵活性,能够决定在运行时调用哪个函数,
在虚拟函数的情况下有一点开销。

In order to achieve this flexibility of being able to decide which function to call at run-time, there is an little overhead in case of virtual functions.

需要执行的额外 fetch 调用,它是使用动态调度支付的开销/价格

An additional fetch call that needs to be performed and it is the overhead/price you pay for using dynamic dispatch.

在非虚函数的情况下,调用的顺序为:

In case of non-virtual function the sequence of calls is:

fetch-call

编译器需要 fetch 函数的地址,然后调用

The compiler needs to fetch address of the function and then call it.

在虚函数的情况下,

fetch-fetch-call

编译器需要中的 vptr fetch ,然后 fetch vptr ,然后 call 函数。

The compiler needs to fetch the vptr from the this, then fetch the address of the function from the vptr and then call the function.

这只是一个简单的解释,实际的顺序可能比这更复杂,但这是你真正需要知道,一个人真的不需要知道执行nitty gritty的。

This is just a simplified explanation the actual sequence maybe far more complex than this but this is what you really need to know, One does not really need to know the implementation nitty gritty's.

良好阅读:

继承与虚拟函数

Inheritance & Virtual Functions

这篇关于虚函数调用和非虚函数调用之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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