Effective C + + clause 7

Source: Internet
Author: User

1. As the polymorphic base class should declare a mass virtual destructor. Assume that the class has a virtual destructor, regardless of the virtual destructor.


2.classed is designed to assume that a virtual destructor should not be declared if it is not used as a base classed, or not for polymorphism.



#include <iostream>using namespace Std;class a{  private:     int i;  Public:     virtual void  Display () {  cout<<i<<endl;}    Virtual ~a () {};      ~a ();     A (): I (0) {}};class b:public a{     Private:     int J;   Public:    void  Display () {  cout<<j<<endl;}     B (): J (1) {}     ~b () {}};iint main () {  A *ptr = new B ();  Ptr->display ();  Delete ptr;  return 0;}

When a class A destructor is not defined as a non-virtual destructor, the compilation will give an error, such as the following


It can be executed normally when defined as a virtual destructor.

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvbml6agfubml6agfu/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/center ">


The problem is that PTR points to a subclass (class B) object, which is deleted by a base class (Class A) pointer, and the base class has a non-virtual destructor.

The subclass component of the run-time object (that is, member variable J, declared in Class B) is not destroyed, and the destructor of the subclass fails to run. However, the base class component is usually destroyed, resulting in a bizarre "partial destruction" object. A resource leak has been created.


No matter what class is only with the virtual function it is almost certain that there should also be a virtual destructor.

Copyright notice: This article Bo Master original article. Blog, not reproduced without consent.

Effective C + + clause 7

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.