Memory leak issues During the inheritance of C + + classes

Source: Internet
Author: User

In the written question, the issue of "memory leaks" is frequently reviewed, one of which is:

A memory leak occurs when a pointer to a base class is pointed to a derived class object that is new, and then the delete pointer is changed.

The reason for this is that the pointer to the base class is pointing to the object of the derived class, the structure of the derived class object has not changed, and when we delete the base class pointer, only the memory of the data member that points to the base class is freed, and the memory that is used by the new member of the derived class still exists, which creates a memory leak

WORKAROUND: Declare the destructor of the base class as a virtual function, which is virtual destructor (virtual).

"Program Instance 1"

1#include <iostream>2 using namespacestd;3 4 classbase{5  Public:6~Base () {7cout<<"Base Deconstructor"<<Endl;8     }9 };Ten  One classDerived: Publicbase{ A  Public: -~Derived () { -cout<<"Derived Desconstuctor"<<Endl; the     } - }; -  - intMain () + { -Base *p=NewDerived; +  A     Deletep; at  -}

"Run Results"

=================================================================

However, when we use the pointer of a derived class to point to a derived class and then delete the pointer, is there a memory leak? (asked a few side of the small partners, the results of a few sure), so the program to speak:

#include <iostream>using namespacestd;classbase{ Public:    ~Base () {cout<<"Base Deconstructor"<<Endl; }};classDerived: Publicbase{ Public:    ~Derived () {cout<<"Derived Desconstuctor"<<Endl; }};intMain () {Derived*p=NewDerived; Deletep;}

"Run Results"

Visible, this is no problem, with the same type of pointer pointing to the same type of object, how can cause problems?

Memory leak issues During the inheritance of C + + classes

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.