为什么抽象类具有vtable? [英] Why does an abstract class have a vtable?

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

问题描述

关于帖子:


对于使用vtable的实现,答案是:是的,通常。您
可能认为抽象类不需要vtable,因为
派生类将具有自己的vtable,但是在
构造过程中需要:在构造基类时,它将
vtable指针设置为其自己的vtable。稍后,当输入派生类
构造函数时,它将使用自己的vtable。

我假设答案是正确的,但我不太明白。为什么vtable确实需要用于构造?

I'm assuming the answer is correct, but I don't quite get it. Why is the vtable needed exactly for construction?

推荐答案

因为标准如此规定。

[class.cdtor] / 4



构造函数或析构函数直接或间接调用虚拟函数时,包括在构造或
销毁期间类的非静态数据成员,调用所应用的
的对象是正在构造或
销毁的对象(称为x),所调用的函数是$ b $中的最终重写器b的构造函数或析构函数的类,而不是在
派生的类中重写它的类。

When a virtual function is called directly or indirectly from a constructor or from a destructor, including during the construction or destruction of the class's non-static data members, and the object to which the call applies is the object (call it x) under construction or destruction, the function called is the final overrider in the constructor's or destructor's class and not one overriding it in a more-derived class.

首先构造基类,然后构造派生类。如果在基类的构造函数中调用了虚函数,则调用派生类将很糟糕,因为派生类尚未初始化。

The rationale is that first the base class is constructed, then the derived one. If a virtual function is called inside the base class' constructor, it would be bad to call the derived class, since the derived class isn't initialized yet.

记住抽象类可能具有非纯虚函数。另外,出于调试目的,最好将纯虚函数指向调试陷阱(例如,MSVC调用 _purecall() )。

Remember that an abstract class may have non-pure virtual functions. Also, for debugging purposes, it is good to point pure virtual functions to a debugging trap (e.g. MSVC calls _purecall()).

如果全部是虚拟的函数是纯函数,在MSVC中,您可以使用 来省略vtable __declspec(novtable) 。如果您使用很多接口类,则可以省去vfptr初始化,从而可以节省大量资金。但是,如果您不小心调用了一个纯虚函数,则将很难调试访问冲突。

If all virtual functions are pure, in MSVC you can omit the vtable with __declspec(novtable). If you use a lot of interface classes, this can lead to significant savings because you omit vfptr initialization. But if you accidentally call a pure virtual function, you'll get a hard to debug access violation.

这篇关于为什么抽象类具有vtable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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