The realization of c++--single case model

Source: Internet
Author: User

Single-Case mode

Concept: A class that can create only one object

Implementation key: 1, all constructors must be private (including parameter constructs, copy constructs, assignment operators)

2. Request the object space through the static member function and return the address

3. Define a static tag, record the number of objects, and control

4. The destructor clears the tag to achieve the purpose of repeating the request object, and the destructor is public

5, the assignment operator, copy constructor must also be private, because the compiler default composition of the assignment operators and copy constructors are public, so both functions are to be defined, and not by the editor default composition

Code implementation:

1#include <iostream>2 3 using namespacestd;4 5 class Single6 {7 Private://because all constructors in singleton mode must be private, all constructors for the compiler's default composition  are public.8Single () =default;//so at this point all constructors have to be defined once9Single (Constsingle&) =default;Tensingle&operator=(Constsingle&) =default; One      A  Public: -     Static intFlag; -     Staticsingle*creat (); the~single ()//The destructor is public -     { -Flag =0; -     } + }; -  + intSingle::flag =0; A  atsingle*single::creat () - { -     if(Flag = =0) -     { -Flag =1; -         return(NewSingle ); in     } -     Else to         returnnullptr; + } -  the  * intMain () $ {Panax NotoginsengSingle *P1 = Single::creat ();//Create an Object -Delete P1;//destroy This object the  +Single *P2 = Single::creat ();//Correct: You can create a new object because the previous object has been destroyed ASingle *P3 = Single::creat ();//Error: The class can only have one unique object, so when P3 is created as nullptr the      +     return 0; -}

The realization of c++--single case model

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.