C ++ stack object and stack object

Source: Internet
Author: User

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 );

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.