The C ++ programming language can be seen as an upgraded version of the C language. Many of its application methods are similar to other programming languages. However, in some specific usage methods, there are still some different application methods. Here we will first look at some special application methods of C ++ destructor.
The Terminator (that is, the destructor) in C # is similar to the C ++ destructor. However, since the execution time of the terminator cannot be determined during compilation, the two are actually quite different. The time when the Garbage Collector calls the C # Terminator is a certain time before the last time the object is used, but before the application is closed. On the contrary, as long as an object (rather than a pointer) is out of the range (the range here refers to the scope), the C ++ destructor will be automatically called. I am a little skeptical about this, so I wrote the C ++ and C # Code respectively to check whether the situation is true.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace ConsoleApplication1
- {
- class Program
- {
- static void Main(string[] args)
- {
- test();
- }
- static void test()
- {
- myPeople p = new myPeople();
- Console.WriteLine("Complate");
- }
- }
- class myPeople
- {
- public myPeople()
- {
- Console.WriteLine("Construct");
- }
- ~myPeople()
- {
- Console.WriteLine("Dispose");
- }
- }
- }
So I inserted a breakpoint in each method and F5 began to debug gradually. I found that the call without myPeople ended the executor call of the Main () method after the test () method was executed. Let's look at C ++.
- #include<iostream>
- #include<string>
- using namespace std;
- class myPeople
- {
- public :
- myPeople()
- {
- cout<<"Construct"<<std::endl;
- }
- ~myPeople()
- {
- cout<<"Dispose"<<std::endl;
- }
- };
- void myMethod()
- {
- myPeople my;;
- cout<<"Complate"<<std::endl;
- }
- int main()
- {
- myMethod();
- }
Through the above execution process, we will find that C # Calls the Terminator is quite different from C ++ destructor, just as the author mentioned above. C # It is not certain to clean up the resources of a class. The release of C ++ class resources starts to call the Destructor after the class has exceeded the scope.