C ++ Singleton Template

Source: Internet
Author: User
/*** @ Template name: MMSCMibSingleton * @ intro: singleton pattern * @ notes: MMSCMibSingleton must be set as a friend class for all classes that inherit the template, and set its own constructor to private */template <typename type> class MMSCMibSingleton {public:/*** get the global sole instance object. if it is null, create it. */static type * GetInstance () {// double judgment to avoid the following coincidence: // when one thread is judging, another thread is still being created, when this thread starts to obtain the lock, another thread is created and left. In this case, the bug is difficult to diagnose, but it exists, especially in the case of high concurrency. If (NULL = m_instance) {pthread_mutex_lock (& m_mutex); if (NULL = m_instance) {m_instance = new type ();} pthread_mutex_unlock (& m_mutex );} return m_instance;}/*** distory the global sole instance object. */static void Destroy () {pthread_mutex_lock (& m_mutex); // you do not need to perform a double check here, because delete null does not cause a bug. if (NULL! = M_instance) {delete m_instance; m_instance = NULL;} pthread_mutex_unlock (& m_mutex);} protected:/*** constructor */MMSCMibSingleton () {pthread_mutex_init (& m_mutex, NULL);}/*** destructor */~ MMSCMibSingleton () {pthread_mutex_destory (& m_mutex);} private: static type * m_instance; pthread_mutex_t m_mutex ;};

Example:

class SubClass:public MMSCMibSingleton<SubClass>{private:    SubClass(){};friend MMSCMibSingleton<SubClass>;};SubClass* SubClass::m_instance = NULL;int main(){    SubClass* clss = SubClass::GetInstance();    //SubClass dsa;//wrong    return 0;}

The implementation of C ++ Singleton is troublesome. You are welcome to provide your own solutions. The multi-thread lock is not required. However, it is necessary to implement Singleton without violating the seven principles of object-oriented design.

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.