没有虚拟构造函数,但有虚拟析构函数 [英] No Virtual constructors but virtual destructor
本文介绍了没有虚拟构造函数,但有虚拟析构函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我们没有虚拟构造函数,那为什么还要有虚拟析构函数呢?构造函数也可以是虚拟的吗?
If we dont have virtual constructors then why we have virtual destructors? Can constructors also be virtual?
推荐答案
- 虚拟构造函数没有意义-您确切声明了什么 类型已创建,并且在编译时众所周知.编译器 不需要[实际上不需要,因为动态分配是基于 关于仅在创建对象之后才创建的信息]. 因此,没有虚拟构造函数.
- 虚拟析构函数对于防止内存泄漏很重要,并且
监视系统.假设您有
A* a = new B;
[B
继承 从A
]开始,之后又是delete a;
-编译器无法 知道a
是B
(在一般情况下),并将调用A
的 析构函数-如果它不是虚拟的,则可能会发生内存泄漏, 或其他故障. - 使用虚拟析构函数-您确保
B
的析构函数为 调用,因为B
对象被破坏. - There is no point in virtual constructor - you declare exactly what type is created, and it is well known in compile time. The compiler do not need [and actually cannot, since the dynamic dispatch is based on information which is created only after the object was created]. So there are no virtual constructors.
- Virtual destructors are important to prevent memory leaks, and
monitor the system. Assume you have
A* a = new B;
[B
inherits fromA
], and you laterdelete a;
- the compiler has no way of knowinga
is aB
[in the general case], and will invokeA
's destructor - if it wasn't virtual, and you might get a memory leak, or other faults. - Using virtual destructor - you ensure that
B
's destructor is invoked, since aB
object is being destroyed.
这篇关于没有虚拟构造函数,但有虚拟析构函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文