Stack objects are equivalent to local objects, and stack objects are equivalent to objects that can be shared with functions or statement blocks. Stack objects are automatically destroyed after the statement block is executed, and the heap objects need to be manually destroyed.
# Include <iostream> using namespace STD; struct object {//★★★★The constructor and type have the same name. No returned type object () {cout <"this is the constructor" <Endl;} // The Destructor name is the type name followed by a Tilde; there is no return value type. ~ Object () {STD: cout <"this is the Destructor! "<Endl ;}}; int main () {// defines an object, which is equivalent to calling the object's constructor O; {object O1; // use the stack object to test the destructor. The partial variable object * O2 = new object will be destroyed during the statement block structure; // define the heap object // Delete O2; // manually destroy the heap object} while (1 );}
Destroy heap object
# Include <iostream> using namespace STD; struct object {//★★★★The constructor and type have the same name. No returned type object () {cout <"this is the constructor" <Endl;} // The Destructor name is the type name followed by a Tilde; there is no return value type. ~ Object () {STD: cout <"this is the Destructor! "<Endl ;}; int main () {// destroy heap object * O1; {O1 = new object ;}delete O1; while (1 );}