Destructor in C++ with Examples

Use destructor to clean up

Destructor is also a special member function, its role is opposite to the constructor, its name The word is a “~” symbol in front of the class name. In C++, “~” is the bitwise negation operator. From this point, you can also think of:

The destructor is the opposite function of the constructor. When the life of the object ends, the destructor will be executed automatically. Specifically, if the following situations occur, complete The sequence will execute the destructor:

1 ) If an object is defined in a function (assuming it is an automatic local object), when the function is called When bundled, the object should be released, and the destructor is automatically executed before the object is released.

2)  The static local object is not released when the function call ends, so the destructor is not called, The destructor of the static local object is only called when the main function ends or the exit function is called to end the program.

3)  If a global object is defined, when the flow of the program leaves its scope (such as the end of the main function) Or call the exit function), call the destructor of the global object.

4)  If an object is dynamically created with the new operator when the object is released with the delete operator, first Call the destructor of the object.

The role of the destructor is not to delete the object, but to complete some cleanup work before the memory occupied by the object is undone. This part of the memory can be allocated to new objects by the program. The programmer must design the destructor in advance to complete the required functions, as long as the life of the object ends, the program automatically executes the destructor to complete these tasks.

The destructor does not return any value, there is no function type, and no function parameters. Since there are no function parameters, It cannot be overloaded. A class can have multiple constructors, but only one destructor. In fact, the role of the destructor is not limited to the release of resources, it can also be used to perform “users want Any operation performed after the last use of the object”, such as outputting relevant information. The user mentioned here is Refers to the designer of the class, because the destructor is defined when the class is declared. That is, the destructor can be done Any operation specified by the designer of the class. Under normal circumstances, the designer of a class should define a destructor at the same time as the class is declared to specify how to complete If the user does not define a destructor, the C++ compilation system will automatically generate a destructor, but it

It just has the name and form of the destructors, in fact nothing is done. Want to let the destructors do any work All operations must be specified in the defined destructor.

Example1 C++ program with constructor and destructor.

operation result:

Program analysis:

Declare the class before the main function, and its scope is global. This can make the main function more concise some. The constructor and destructor are defined in the Student class. Create the object first when executing the main function stud1, call the object’s constructor when creating an object, and assign initial values ​​to the data members of the object. Then call stud1 The display function, output the value of the data member of stud. Then create the object stud2, which is called when the object is created The constructor of stud2, and then call the display function of stud2, output the value of the data member of stud2.

At this point, the statement in the main function has been executed, and the call to the main function is over. The object created in the main function It is partial, and its lifetime ends with the end of the main function. The last work before the object is to be cancelled is to call Destructor. In this case, the destructor does not have any substantial effect, it just outputs a message. We are here It is used only to illustrate the use of destructors. Which object’s destructor output the last two lines? It is explained in the brackets on the right side of the line, please read Let’s think about it first, and we’ll explain it further in the next section.

 The order of calling the constructor and destructor

When using the constructor and destructor, you need to pay special attention to their calling time and calling sequence. When some readers saw the last two lines of the program output in Example 1 as you can see in above, they thought that the right parentheses of the two lines The description inside is wrong. Many people will naturally think: it should first execute the destructor of stud1, and then execute The destructor of stud2. Are stud1 and stud2 in the book Is it reversed? However, it was these readers who got it wrong. In general In this case, the order of calling the destructor is exactly the same as that of calling the constructor. The order is reversed: the constructor that is called first, and its corresponding (same The destructors in the object is called last, and the last called Constructor, its corresponding destructor is called first, such as As shown in below figure

It can be abbreviated as: first constructed and then destructed, then constructed The first destruction. It is equivalent to a stack, first in and last out. Readers may not worry: how do you know that the first execution is What about the destructor of stud2? Please think of a method by yourself first To verify. Here is a simple method: set the Student class The function body of the destructor of the meaning is changed to.

cout << “Destructor called.” << num << endl;

That is, add an item num when outputting, and output the value (student number) of the data member num in this object. So you can output from In the result, the student’s student ID of which object is output is analyzed to determine which object’s destructor is executed. The last two behaviors of the modified operation result

Destructor called.10011

Destructor called .10010

10011 is the value of member num in the object stud2, and 10010 is the value of member num in the object stud1. the first construction is followed by the destruction, and the second construction is the first destruction. As mentioned above: In general, the order of calling the destructor is opposite to the order of calling the constructor. this is For objects of the same storage category. For example, stud1 and stud2 in the program in Example 1 are in the same function The defined local functions have the same characteristics, According to the principle of “construct first and then destruct, and then destruct first”. However, this principle is not always handled under all circumstances. I have introduced the role when learning C language

The concepts of domain and storage category are also applicable to objects. Objects can be defined in different scopes, There can be different storage categories. These will affect the timing of calling the constructors and destructors. The following summarizes when the system calls the constructor and destructor:

(1) If an object is defined in the global scope (that is, an object defined outside of all functions), then its constructor It is called before all functions (including main function) in this file module are executed. But if a program contains multiple Files, and global objects are defined in different files, the execution order of the constructors of these objects is incorrect Fixed. When the main function is executed or the exit function is called (the program terminates at this time), the destructor is called.

(2) If the definition is a local automatic object (for example, an object is defined in a function), it is called when the object is created. Constructor. If the function of the object is called multiple times, the constructor must be called every time the object is created. The destructor is called first when the function call ends and the object is released.

(3) If a static (Static) local object is defined in the function, the function definition pair is only called for the first time in the program. The constructor is called once when the image is called, and the object is not released when the calling function ends, so the destructor is not called, only in The destructor is only called when the main function ends or the exit function is called to end the program. For example, two objects are defined in a function:

void fn() {

Student stud1;

static Student stud2;


When calling the in function, first create the stud1 object, call the stud1 constructor, and then create the stud2 object, call Use the stud2 constructor. At the end of the call, the object stud1 is to be released (because it is an automatic local pair Like), so the destructor of stud1 is called. And stud2 is a static local object, which is not released at the end of the n call. Therefore, the destructor of stud2 is not called. Until the end of the program release stud2, the destructor of stud2 is called. You can see that stud2 calls the constructor later, but does not call its destructor first. The reason is the existence of two objects Different storage categories and different life cycles. Constructor and destructor are very important in object-oriented programming and are one of the design of classes important part.

Description: In above, the method of assigning initial values ​​to the data members of the class object through the constructor. Some readers may find it too complicated and difficult To master. It should be noted that the constructor is defined by the designer of the class, or in other words, is part of the declaration of a class. In general, the designer (declarator) of the class and the user of the class are not the same person. Declared in the header file After the class (including the definition of the constructor), the user can use this class as long as the file is included with the #include directive Define the object. It is relatively simple to initialize when the object is defined, such as

Box box (15,30,20);      //3 initial values ​​are given

when defining the object box As a user, you don’t need to care about the specific writing of the constructor and the details of how to assign the initial value in the constructor, as long as you know The prototype of the constructor (knowing that there are several formal parameters, the types and order of the formal parameters) and the way to use it, there is no need Programmers who want C++ write their own constructors.

Related Article:




Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button