Why are destructors not virtual by default?
来源:互联网 发布:通达信布林线公式源码 编辑:程序博客网 时间:2024/05/20 17:24
Because many classes are not designed to be used as base classes. Virtual functions make sense only in classes meant to act as interfaces to objects of derived classes (typically allocated on a heap and accessed through pointers or references).
Had Base's destructor not been virtual, Derived's destructor would not have been called - with likely bad effects, such as resources owned by Derived not being freed.
So when should I declare a destructor virtual?Whenever the class has at least one virtual function. Having virtual functions indicate that a class is meant to act as an interface to derived classes, and when it is, an object of a derived class may be destroyed through a pointer to the base. For example:
class Base {// ...virtual ~Base();};class Derived : public Base {// ...~Derived();};void f(){Base* p = new Derived;delete p;// virtual destructor used to ensure that ~Derived is called}
Had Base's destructor not been virtual, Derived's destructor would not have been called - with likely bad effects, such as resources owned by Derived not being freed.
- Why are destructors not virtual by default?
- Failed to write core dump. Minidumps are not enabled by default on client versions of Windows
- Failed to write core dump. Minidumps are not enabled by default on client versions of Windows
- Failed to write core dump. minidumps are not enabled by default on client version of windows
- 【Xuggle】Failed to write core dump. Minidumps are not enabled by default on client versions
- Why are you still not using Hudson?
- Eclipse 运行崩溃 报错 Failed to write core dump. Minidumps are not enabled by default on client versions解决
- Why are EPS files generated by gnuplot rotated 90 degrees?
- Why not implement deep copy in default copy constructor?
- Somebody~why I can not be there where you are??????????????
- Why are MVC & TDD not employed more in game architecture?
- Why multiple inheritances are not supported in Java
- Do what you love: Why you are not your job
- Java - Why multiple inheritances are not supported in Java
- Why the default eth0 interface is down by default on CentOS?
- Why does wide file-stream in C++ narrow written data by default?
- Why not ?
- Why are you crying?
- seandroid对selinux的改进
- Java中一个简单易用的JAD 反编译工具
- STL经典算法集锦之排列(next_permutation/prev_permutation
- ubuntu12.04 安装chromium
- 关于System.out.println
- Why are destructors not virtual by default?
- 黑马程序员----JAVA----基础小结----
- 在Openssl 0.9.7c 下找不到 SHA512 算法
- Dalvik虚拟机即时编译系统在unicore上的移植
- MATLAB——scatter的简单应用
- SEQ ACK
- TVS管
- CodeBlocks下如何给main函数传递参数
- 安装rar(这个太常用了)