什么可以导致在C ++纯虚拟函数调用? [英] What can cause a pure virtual function call in C++?

查看:164
本文介绍了什么可以导致在C ++纯虚拟函数调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我教一个C ++编程类,我看到了足够多的错误,我有一个很好的感觉,如何诊断常见的C ++错误。但是,有一种主要类型的错误,我的直觉不是特别好:什么编程错误导致调用纯虚拟函数?最常见的错误,我看到,导致这是调用虚拟函数从基类构造函数或析构函数。在帮助调试学生代码时,应该注意哪些其他问题?

I teach a C++ programming class and I've seen enough classes of errors that I have a good feeling for how to diagnose common C++ bugs. However, there's one major type of error for which my intuition isn't particularly good: what programming errors cause calls to pure virtual functions? The most common error I've seen that causes this is calling a virtual function from a base class constructor or destructor. Are there any others I should be aware of when helping debug student code?

推荐答案


常见的错误我已经看到,原因是从基类构造函数或析构函数调用虚函数。

"The most common error I've seen that causes this is calling a virtual function from a base class constructor or destructor."

构造的,指向虚拟分派表的指针最初指向最高的超类,并且仅当中间类完成构建时才更新。所以,你可以不小心调用纯虚拟实现,直到一个子类 - 它自己的覆盖函数实现 - 完成构建。

When an object is constructed, the pointer to the virtual dispatch table is initially aimed at the highest superclass, and it's only updated as the intermediate classes complete construction. So, you can accidentally call the pure virtual implementation up until the point that a subclass - with its own overriding function implementation - completes construction. That might be the most-derived subclass, or anywhere in between.

这可能会发生,如果你遵循一个指向一个部分构造的对象的指针(例如在竞争条件,由于异步或线程操作)。

It might happen if you follow a pointer to a partially constructed object (e.g. in a race condition due to async or threaded operations).

如果编译器有理由认为它知道指针到基类指向的实际类型,它可以合理地绕过虚拟分派。你可能会通过做一些未定义的行为像一个重新解释转换来混淆它。

If a compiler has reason to think it knows the real type to which a pointer-to-base-class points, it may reasonably bypass the virtual dispatch. You might confuse it by doing something with undefined behaviour like a reinterpret cast.

在销毁期间,虚拟分派表应该被还原为派生类被销毁,所以纯虚拟

During destruction, the virtual dispatch table should be reverted as derived classes are destroyed, so the pure virtual implementation may again be invoked.

在销毁之后,通过悬挂指针或引用继续使用对象可以调用纯虚函数,但是在这种情况下没有定义的行为情况。

After destruction, continued use of the object via "dangling" pointers or references may invoke the pure virtual function, but there's no defined behaviour in such situations.

这篇关于什么可以导致在C ++纯虚拟函数调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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