C ++ Singleton Mode

Source: Internet
Author: User

Singleton mode: Only one object can be generated for each class.

 

# Include <stdio. h>

Class
{
PRIVATE:
Int ID;
A () {} // place the constructor in private: the objective is to not directly allocate space definition objects on the stack outside the class.

 

Public:
Static A * PT;
Static A * instance ()
{
If (Pt = NULL) // note that it is a double equal sign, and it seems that it is difficult to use null in C ++.
{
PT = new;
Return pt;
}
Else
Return pt;
}

~ A ()
{
Delete pt; // because the heap space is opened, delete is used for release.
}

 

Void id_set (int x)
{
Id = X;
}


Void id_get ()
{
Printf ("% d", ID );
}
 
};

 

A * A: Pt = NULL; // static member variables can only be initialized outside the class.

 

Int main ()
{

// This class cannot allocate objects on the stack. Objects can only be allocated on the stack using the new function interface provided in the class.
A * PPT = A: instance ();
PPT-> id_set (10 );
PPT-> id_get ();

A * ppt1 = A: instance ();
Ppt1-> id_get ();
Ppt1-> id_set (5 );

PPT-> id_get ();
Return 0; // automatically call the Destructor at the end of the Function ~ A ();
}

 

 

The output is 10105

The ppt and ppt1 point to the same object.

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.