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.