An important role of constructor is to apply for resources for objects. Correspondingly, the Destructor is responsible for releasing these resources. The following describes the Destructor:
When to call the Destructor: (see section C ++ prime page 412)
The Destructor is automatically called when the class object is revoked; the variable is automatically revoked when the scope is exceeded; the dynamically allocated object is revoked only when the pointer pointing to the team is deleted; if the pointer to a dynamic object is not deleted, the destructor of the object will not be run and the object will always exist, resulting in Memory leakage. PS: when the object reference or pointer exceeds the scope, the Destructor is not run. Only when the pointer pointing to the dynamically assigned object or the actual object (rather than the object reference) is deleted out of scope will the Destructor be run.
Next we will look into this rule:
# Include <string. h >#include <vector >#include <iostream> using namespace STD; int I = 0; Int J = 0; Class cdemo {public: cdemo (): STR (null) {cout <"constructor _" <I ++ <Endl ;}; cdemo (const cdemo & CD) {cout <"constructor _" <I ++ <Endl; this-> STR = new char [strlen (CD. str) + 1]; strcpy (STR, CD. str );};~ Cdemo () {cout <"destrcutor _" <j ++ <Endl; If (STR) Delete [] STR ;}; char * STR ;}; int main () {cdemo * pdemo = new cdemo (); cout <"R1" <Endl; {cdemo D1; cdemo & D2 = D1; d2.str = new char [32]; strcpy (d2.str, "Hello wordl");} cout <"R2" <Endl; pdemo-> STR = new char [32]; strcpy (pdemo-> STR, "this is pdemo2"); Delete pdemo ;}
ProgramOutput result
Constructor_0r1constructor_1destructor_0r2destructor_1
Comply with the preceding rules.