在 C++ 编译期间,'有虚拟方法......但非虚拟析构函数'警告是什么意思?
问题描述
有编译警告
如何理解这个警告以及如何改进代码?
How to understand this warning and how to improve the code?
这个版本现在正确吗?(试图给出答案以阐明自己的概念)
is this version correct now? (Trying to give answer to elucidate myself with the concept)
推荐答案
如果一个类有虚方法,那意味着你希望其他类继承它.这些类可以通过基类引用或指针来销毁,但这仅在基类具有虚拟析构函数时才有效.如果你有一个应该可以多态使用的类,那么它也应该可以多态删除.
If a class has a virtual method, that means you want other classes to inherit from it. These classes could be destroyed through a base-class-reference or pointer, but this would only work if the base-class has a virtual destructor. If you have a class that is supposed to be usable polymorphically, it should also be deletable polymorphically.
这里也深入回答了这个问题.下面是一个完整的示例程序,演示效果:
This question is also answered in depth here. The following is a complete example program that demonstrates the effect:
输出:
注意 delete bar;
导致析构函数 ~Bar
和 ~BarBase
被调用,而 delete foo;
只调用 ~FooBase
.后者甚至是未定义行为,因此无法保证效果.
Note that delete bar;
causes both destructors, ~Bar
and ~BarBase
, to be called, while delete foo;
only calls ~FooBase
. The latter is even undefined behavior, so that effect is not guaranteed.
这篇关于在 C++ 编译期间,'有虚拟方法......但非虚拟析构函数'警告是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!