When to call the destructor

Source: Internet
Author: User

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.

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.