Situ zhengmei
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 and no return value type.
Object (){
Cout <"this is a constructor" <endl;
}
// The Destructor name is a type name prefixed with a Tilde character, and there is no return type.
~ Object (){
Std: cout <"this is the Destructor! "<Endl;
}
};
Int main (){
// Define an object, which is equivalent to calling the constructor of this object.
Object o;
{
Object o1; // use a stack Object to test the destructor. Partial Variables are naturally destroyed when the block structure of a statement is used.
Object * o2 = new Object; // defines 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 and no return value type.
Object (){
Cout <"this is a constructor" <endl;
}
// The Destructor name is a type name prefixed with a Tilde character, and there is no return type.
~ Object (){
Std: cout <"this is the Destructor! "<Endl;
}
};
Int main (){
// Destroy the heap object
Object * o1;
{
O1 = new Object;
}
Delete o1;
While (1 );
}