In C ++, how does one clear objects to be destroyed? Can the C ++ compiler automatically call a special function to clear objects ?, Destroy Compiler

Source: Internet
Author: User

In C ++, how does one clear objects to be destroyed? Can the C ++ compiler automatically call a special function to clear objects ?, Destroy Compiler

Objects in life are listed after initialization. Objects in life will do some work before they are destroyed.

Question 1: How to clear objects to be destroyed in C ++?

In general, all objects to be destroyed should be cleaned up.

To provide a public free function object for each class, call the free function to clean up immediately if it is no longer needed.

Class Test {int * p; public: Test () {p = new int ;}; void free () {delete p ;};};

Problems

Free is just a common function. It must be displayed that the called object is not cleared before destruction, which may cause resource leakage.

Question 2: Can the C ++ compiler automatically call a special function to clear objects? Destructor

A special cleaning function can be defined in the C ++ class.

This special cleanup function is called a destructor. The function of the Destructor is opposite to that of the constructor.

Definition :~ ClassName ()

The Destructor has no parameters and no return value. type declaration. The Destructor automatically calls the Destructor when the object is destroyed.

When the class has a self-defined constructor and the constructor uses system resources (such as memory application, file opening, and so on), the constructor must be automatically used as the destructor.

Summary

The Destructor is a special function that is cleaned up when an object is destroyed. The Destructor is automatically called when the object is destroyed, which guarantees that the object can release system resources.

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.