为什么需要虚拟关键字? [英] Why is the virtual keyword needed?

查看:143
本文介绍了为什么需要虚拟关键字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

换句话说,为什么编译器不知道如果函数的定义在派生类中被改变,并且指向动态分配的该派生类的内存的指针调用被改变的函数,那么该函数



在什么情况下不会让虚拟关键字对程序员的好处起作用?


<关键字告诉编译器实现动态分派。 语言设计。
没有这样的关键字,编译器不知道是否实现动态分派。



virtual 或动态分派一般是




  • 它具有轻微的性能损失。大多数编译器将使用vtable和vptr机制实现动态分派,其中通过vtable决定适当的调用函数,因此在动态分派的情况下需要额外的间接。

  • 非POD。


In other words, why doesn't the compiler just "know" that if the definition of a function is changed in a derived class, and a pointer to dynamically allocated memory of that derived class calls the changed function, then that function in particular should be called and not the base class's?

In what instances would not having the virtual keyword work to a programmer's benefit?

解决方案

virtual keyword tells the compiler to implement dynamic dispatch.That is how the language was designed. Without such an keyword the compiler would not know whether or not to implement dynamic dispatch.

The downside of virtual or dynamic dispatch in general is that,

  • It has slight performance penalty. Most compilers would implement dynamic dispatch using vtable and vptr mechanism, where the appropriate function to call is decided through vtable and hence an additional indirection is needed in case of dynamic dispatch.
  • It makes your class Non-POD.

这篇关于为什么需要虚拟关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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