C ++ trap: virtual destructor

Source: Internet
Author: User

One day a colleague was debugging a memory leak problem through vld. After a long time, he found me. I glanced at his code and found that the problem was exactly the same as what I encountered:

Class Base {
Public:
~ Base ();
};

Class Derived: public Base {
Privated:
Std: vector <int> m_data;
};

Base * obj = new Derived ();
Delete obj;
Of course, the actual code is much more complicated than this (this is also the reason that it takes a lot of time to discover the problem ). When vld reports a memory leak, the location of the error is new. This colleague checked the entire lifecycle of the object and confirmed that he correctly released the object.

The key to the problem is that the destructor of the Base class is not virtual. Because it is not virtual, When deleting a Base-type pointer, it will not call the Derived destructor of the Derived class. The destructor in the derived class is used to analyze the internal sub-objects, that is, m_data. In this way, memory leakage occurs.

This is actually a very low-level mistake. But it is not polite to say that C ++ has many examples where such a keyword or code location is incorrect may lead to another result. As a matter of fact, many books have come up with some guidelines for these tragedies to make them easy to follow. For example, I remember a book saying that if you think your class will be inherited, you 'd better add virtual to the destructor.

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.