C + + virtual destructor [avoid memory leaks]

Source: Internet
Author: User

C + + Virtual destructor:

Virtual destructor
(1) The virtual destructor is the definition of the Declaration destructor before the virtual modification, if the destructor of the base class is declared as a virtual destructor,
The destructor for all derived classes derived from the base class is also automatically a virtual destructor.

(2) Base class pointer pbase to a derived class object created with new dynamically child, with "delete pbase;" There are two cases of deleting objects:
First, if the destructor in the base class is a virtual destructor, the derived class object is deleted before the base class object is deleted
Second, if the destructor in the base class is a non-virtual destructor, only the base class object will be deleted, and the derived class object will not be deleted, so there is a memory leak

#include <iostream>using namespacestd; #include<string>//////////////////////////// classBase { Public:#if0Virtual~base ();//In Child::~child () in Base::~base ()#else~base (); //  in Base::~base () risk of memory leaks #endif}; Base::~Base () {cout<<"In base::~base ()"<<Endl;}////////////////////////////classChild: PublicBase { Public:    ~Child ();}; Child::~Child () {cout<<"In child::~child ()"<<Endl;}intDemo () { Base *PC =NewChild  ; cout<<"-----------"<<Endl;    Delete pc; cout<<"-----------"<<Endl; return 0 ;}intMain () {demo ();  while(1); return 0;}

C + + virtual destructor [avoid memory leaks]

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.