Singleton implementation in C ++

Source: Internet
Author: User

Singleton implementation in C ++

Keywords: ansi c ++, Singleton, static member, initialize, auto_ptr, STD, STL, implement, implementation

The Singleton implementation in ansi c ++ is not difficult, and it is not easy to say. Many people write errors in the singleton class of ansi c ++. This article discusses how to write Singleton class in ansi c ++, hoping to help you.

In design pattern, write Singleton as the return pointer:

Class Singleton {
Public:
Static Singleton * instance ();
Protected:
Singleton ();
PRIVATE:
Static Singleton * _ instance;
};

The corresponding implementation CPP file is:

Singleton * singleton: _ instance;
Singleton * singleton: instance (){
If (_ instance = 0 ){
_ Instance = new Singleton;
};
Return _ instance;
}

The purpose of designing the constructor as protected is to prevent the new class from being out of the class. Some people may design it as private. If this class may be inherited, it is better to design the constructor to protected, and you also need to add a virtual destructor. To prevent others from copying Singleton objects:
Singleton * psingleton = singleton: instance ();
Singleton S1 = * psingleton;
Singleton S2 = * psingleton;
You need to convert the copy constructor function to private.

However, the question is, when will the singleton object be deleted? According to a basic principle of C ++, where an object is created and destroyed, a destroy method should be used to delete the singleton object. If you forget to delete it, it will be troublesome. The instance function also has the issue of simultaneous multi-threaded access locks. If you lock and unlock the start and end of the Instance function, the overall function performance will decrease a lot. This is not a good design.
There is a small change to avoid the memory leakage caused by forgetting to delete the singleton object. STD: auto_ptr is used to include the singleton object, define a class static member auto_ptr object, and automatically delete the singleton object when parsing the static auto_ptr variable. To prevent users from deleting Singleton objects, you need to change the Destructor from public to protected. The following is the header file singletonautoptr. h:

# Include <memory>
Using namespace STD;
Class csingletonautoptr
{
PRIVATE:
Static auto_ptr M_auto_ptr;
Static csingletonautoptr * m_instance;
Protected:
Csingletonautoptr ();
Csingletonautoptr (const csingletonautoptr &);
Virtual ~ Csingletonautoptr ();
// Allow auto_ptr to delete, using protected ~ Csingletonautoptr ()
Friend class auto_ptr ;
Public:
Static csingletonautoptr * getinstance ();
Void test ();
};

The corresponding singletonautoptr. cpp is as follows:

# Include "singletonautoptr. H"
# Include <iostream>

// Initial static member vars here
Csingletonautoptr * csingletonautoptr: m_instance = NULL;
Auto_ptr Csingletonautoptr: m_auto_ptr;

//////////////////////////////////////// //////////////////////////////
// Construction/destruction
//////////////////////////////////////// //////////////////////////////
Csingletonautoptr: csingletonautoptr ()
{
Cout <"csingletonautoptr: csingletonautoptr ()" <Endl;
// Put single object into auto_ptr object
M_auto_ptr = auto_ptr (This );
}

Csingletonautoptr ::~ Csingletonautoptr ()
{
Cout <"csingletonautoptr ::~ Csingletonautoptr () "<Endl;
}

Csingletonautoptr * csingletonautoptr: getinstance ()
{
// Begin lock
//....

If (m_instance = NULL)
M_instance = new csingletonautoptr ();

// End lock
//...

Return m_instance;
}

Void csingletonautoptr: Test ()
{
Cout <"csingletonautoptr: Test ()" <Endl;
}

Call method:

Csingletonautoptr * psingleton = csingletonautoptr: getinstance ();
Psingleton-> test ();

Writing a singleton in C ++ requires so much effort as we expected. Many people have never used auto_ptr, and STD: auto_ptr itself is not perfect. It is based on the object ownership mechanism. In contrast, there is an auto_ptr in Apache log4cxx, which is based on the object count, easier to use. Log4cxx is only used to use a good auto_ptr, which is not good for many projects. Of course, STD: auto_ptr in STL of ansi c ++ is enough for the written example.

Another idea is that it may be better to design the getinstance function to static member, because generally, Singleton objects are not large. Although static member must always occupy memory, it is not a problem. The Destructor must be set to public. The following is the header file singlestaticobj. h.

Class csingletonstaticobj
{
PRIVATE:
Static csingletonstaticobj m_instance;
Protected:
Csingletonstaticobj ();
Csingletonstaticobj (const csingletonstaticobj &);
Public:
Virtual ~ Csingletonstaticobj (); // must public
Static csingletonstaticobj & getinstance ();
Void test ();
};

The corresponding singlestaticobj. cpp file is:

# Include "singletonstaticobj. H"
# Include <string>
# Include <iostream>
Using namespace STD;

Csingletonstaticobj: m_instance;

Csingletonstaticobj: csingletonstaticobj ()
{
Cout <"csingletonstaticobj: csingletonstaticobj ()" <Endl;
}

Csingletonstaticobj ::~ Csingletonstaticobj ()
{
Cout <"csingletonstaticobj ::~ Csingletonstaticobj () "<Endl;
}

Csingletonstaticobj & csingletonstaticobj: getinstance ()
{
Return m_instance;
}

Void csingletonstaticobj: Test ()
{
Cout <"csingletonstaticobj: Test ()" <Endl;
}

Call method:

Csingletonstaticobj & Singleton = csingletonautoptr: getinstance ();
Singleton. Test ();

In terms of the amount of code, it seems easier to use static member ref. I prefer this method.

However, static member Singleton is not applicable in all cases. For example, when getinstance dynamically decides to return different instances, it cannot be used. For example, if filesystem: getinstance is run in windows, new winfilesystem may be returned. If it is run in Linux/Unix, new linuxfilesystem may be returned, in this case, you still need to use the auto_ptr method that includes the singleton pointer.

How to Write Singleton depends on your project needs.
The above code is compiled under Visual C ++ 6.0.

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.