"Effective C + +" Reading Note 07: Declaring a virtual destructor for a polymorphic base class

Source: Internet
Author: User
Tags data structures

This problem is occasionally encountered in practice, designing a timekeeper base class and some derived classes to record the time:

1 class TimeKeeper
2 {
3 public:
4   TimeKeeper ();
5   ~TimeKeeper();
6
7 };
8
9 class AtomicClock: public TimeKeeper {}; //原子钟
10 class WaterClock: public TimeKeeper {}; //水钟

When using, we may use the Factory factory method:

1 TimeKeeper* getTimeKeeper();//返回一个指针,指向一个派生类的动态分 配的对象
2
3 TimeKeeper* ptk = getTimeKeeper();//从继承体系中得到一 个动态分配对象
4
5 delete ptk;//负责的删除它

The problem occurs when you delete it, because PTK this pointer to the base class, the deleted instruction executes the base class Timekeeper destructor, which is not a virtual function.

In C + +, in this case its deletion behavior is not defined, the general will only delete the base class components, and the derived class elements are not deleted, which is the formation of resource leaks, corrupted data structures, the debugger waste a lot of time on the best way to Oh (quote the original translation).

The solution is to define a virtual destructor for a base class, so that the deletion behavior is implemented in the derived class, not just part of the deletion.

In general, a virtual destructor is defined as long as there is a virtual function in the class. However, if you do not have a virtual function in a class, you do not need and should not define a virtual destructor, which is not only useless, but also adds additional expense and creates a lot of compatibility problems because the virtual mechanism is unique to C + +.

In addition, many classes in C + + implementations are not virtual, such as: String,stl in the Vector,list, Set,trl::unordered_map, if you inherit them is likely to be the error, so the author reminded : Reject inheritance of standard containers or other classes that have only non-virtual destructors!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.