C + + base class pointers to the release of derived class object memory

Source: Internet
Author: User
C + + because the base-class pointers can point to different derived class objects, you should be aware of the memory deallocation of the previous derived class object when assigning different addresses to the base class pointers.
int main () {parent* ptr = new Child1; Child2 myChild2; Child3 mychild3;ptr->show ();d elete ptr;//Position 1ptr = &mychild2;ptr->show ();d elete ptr;//Position 2ptr = &mychild3 ;p tr->show ();d elete ptr;//position 3system ("pause"); return 0;}
In this code, only position 1 can release the memory that PTR points to, position 2, Position 3 is wrong.
Because only the memory that PTR points to at the beginning is dynamically allocated (new), it is created on the heap, and the mychild2,mychild3 memory is on the stack, and it is automatically released when the program ends. After releasing memory at location 1, there is no memory allocated dynamically, so delete ptr can no longer be used. Release is required unless PTR = new Child2 is used before position 2, and a memory is dynamically allocated for the Child2 class.

and position 1 Delete ptr, also necessary because if the Child1 object memory,ptr=&mychild2; is not released here, there will be a memory leak with no pointer pointing to Child1 memory.

In addition,when you delete ptr, the compiler only knows that the pointer is of type "pointer to base class" and does not know the type of object it actually points to. Therefore, if the base class does not use a virtual destructor, the compiler can only call the destructor of the base class when delete ptr, and cannot invoke the destructor of the derived class, and cannot release the dynamic memory that the derived class might allocate.

The solution is to dynamically parse the call to the destructor when the program executes, destroying all dynamically allocated memory by using the virtual destructor in the base class.

C + + base class pointers to the release of derived class object memory

Related Article

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.