派生类和基类都需要虚拟析构函数吗?
假设我们有以下内容:
#include <iostream>
struct A
{
virtual ~A() { std::cout << "destr A\n"; }
};
struct B : A
{
// no need to be virtual?
~B() { std::cout << "destr B\n"; }
};
struct C : B
{
~C() { std::cout << "destr C\n"; }
};
现在,我创建一个 C
实例并将其分配给其基类 B
的指针。
int main()
{
B* b = new C{};
delete b;
return 0;
}
输出是:
destr C
destr B
destr A
让我有点惊讶的是对象被正确销毁(所有三个析构函数都被调用)。根据输出,我会说 ~B()
是一个虚拟析构函数:~B()
分派到 ~C()
,然后~B()
完成,最后调用 ~A()
。这个说法正确吗?
我知道,如果基类的某些函数是虚拟的,则派生类中重写基类中的函数的函数也是虚拟的。我不知道析构函数也是如此。因为我使用 virtual
函数说明符声明了 ~A()
,所以 ~B()
是虚拟的吗?
Say we have the following:
#include <iostream>
struct A
{
virtual ~A() { std::cout << "destr A\n"; }
};
struct B : A
{
// no need to be virtual?
~B() { std::cout << "destr B\n"; }
};
struct C : B
{
~C() { std::cout << "destr C\n"; }
};
Now, I create an instance of C
and assign it to a pointer of its base class B
.
int main()
{
B* b = new C{};
delete b;
return 0;
}
The output is:
destr C
destr B
destr A
What surprised me a little is that the object gets destroyed correctly (all three destructors are called). According to the output, I would say ~B()
is a virtual destructor: ~B()
dispatches to ~C()
, then ~B()
finishes and finally, ~A()
is called. Is this statement correct?
I know that, if some function of a base class is virtual, the function in the derived class which overrides the one in the base class is virtual as well. I did not know that was true for destructors as well. Is ~B()
virtual because I declared ~A()
with the virtual
function specifier?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的。根据 https://timsong-cpp.github.io/cppwp/n4659 /class.dtor#10:
Yes. Per https://timsong-cpp.github.io/cppwp/n4659/class.dtor#10: