1. What is a destructor
a destructor (destructor) is also a member function, but it acts in the opposite of a constructor to do some cleanup before the system releases the object, such as releasing temporarily allocated memory using the delete operator, clearing 0 of some memory units, and so on. When the lifetime of an object ends, the system automatically calls the destructor of the class to which the object belongs;
The name of the constructor is the same as the class name, and the name of the destructor must precede the class name with a "~" symbol; note that constructors and destructors cannot specify any return value types, including void return types.
2. When to call a destructor
The destructor is automatically called when the class object is revoked (the variable should be automatically revoked when it goes out of scope), and the dynamically allocated object is revoked only if the pointer to the object is deleted.
#include <iostream>using namespace Std;class test{public : Test () {} ~test () { cout< < "This is a ~test ()" <<endl; } ; int main () { Test A; Test *ptr = new test (); Delete ptr;
The program calls two destructors, the first time when PTR is removed, and the second time when the closing parenthesis is encountered.
If a class requires a destructor, it also requires an assignment operator and a copy constructor, which is a useful rule of thumb.
4. Composition destructor
Unlike a copy constructor or assignment operator, the compiler always synthesizes a destructor for us . The composition destructor revokes each non-static member in reverse order when the object is created, so that it revokes the member in the reverse sequence of declaring the member in the class. For each member of the class type, the composition destructor calls the member's destructor to undo the object.
5. Virtual destructor and pure virtual destructor, here directly to send a link, is someone else wrote the blog, speak very good click to open the link.
The destructor of C + + replication control