Single-Instance mode implementation

Source: Internet
Author: User

This is a single-instance template class

#pragmaOnceTemplate<typename t>classcsingletont{ Public:    StaticS MInstance () {returnM_pobj; }    classCdeconstructor { Public: Cdeconstructor () {if(NULL = =m_pobj) {M_pobj=NewT (); }        }        ~Cdeconstructor () {if(csingletont::m_pobj) {DeleteCsingletont::m_pobj; Csingletont::m_pobj=NULL; }        }    };protected: Csingletont (void){}    Virtual~csingletont (void){}protected:    StaticS MM_pobj; Staticcdeconstructor M_dec;};

Inherit this template when you use it, such as:

#pragmaOnce#include"WebRef.h"#include"SingletonT.h"usingService1::CService1;classCwebaccess: Public csingletont<cwebaccess>{friendclassCsingletont<cwebaccess>; FriendclassCsingletont<cwebaccess>:: cdeconstructor; Public: CService1*GetService (); voidSetserviceurl (Constcstring&strURL);protected: CService1 m_service; Virtual~cwebaccess (void) {} cwebaccess (void){}}; Csingletont<cwebaccess>::cdeconstructor csingletont<cwebaccess>:: M_dec; Cwebaccess* Csingletont<cwebaccess>::m_pobj = NULL;

Two static for the template class to define, the header file is just a declaration. Since M_dec is a static member, it is constructed before the main function executes, and the main exits after the destructor, so this feature is used to create a singleton instance variable so that thread safety can be implemented without locking. A good structure is that the main function does not have multiple threads before main.

Single-Instance mode implementation

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.