Question 2. When to execute constructors and destructors 22:59:40 2015-07-22
An experiment was done:
#include <iostream>class object{public: Object () { printf ("Create object\n"); }; ~Object () { printf ("Delete object\n");} }; void Runobject () {Object obj; printf ("Runobject end\n");} int Main () {//Object *obj=new object ();//delete obj; runobject (); printf ("end\n"); return 0;}
The output is:
Create Object
Runobject End
Delete Object
End
Add a {} in void Runobject ()
#include <iostream>class object{public: Object () { printf ("Create object\n"); }; ~Object () { printf ("Delete object\n");} }; void Runobject () {{Object obj;} printf ("Runobject end\n");} int Main () {//Object *obj=new object ();//delete obj; runobject (); printf ("end\n"); return 0;}
The output is:
Create Object
Delete Object
Runobject End
End
C + + Learning notes--constructors and destructors