Singleton single-Case mode

Source: Internet
Author: User

#include <iostream>#include <windows.h>#include <mutex>using namespace STD;STD:: Mutex _smutex;Template<TypeNameType>classsingleton{ Public:Statictype* Getsigleton () {if(Singlen = = NULL) {unique_lock<STD::mutex> Lock (_smutex);//c++11 the lock syntax.             after the end of the//unique_lock life cycle, the lock objects it manages are unlocked,            if(Singlen = = NULL) {#ifndef _win32#define _WIN32#endiftype* tmp =NewType (); Memorybarrier ();//Fence allows the previous code to execute before executing, preventing CPU optimizations causing confusion in multithreaded code execution. Singlen = tmp;//If direct Signlen = new Type ();//Here you have the space, call the construct,       //Assignment Three-step operation may be confusing. }        }returnSinglen; }Private:StaticType *singlen;//Prevent optimization so that each Singlen value is in memory. };Template<TypeNameType>type * Singleton<type>::singlen = NULL;classtest{ Public:voidPrintf () {cout<<"This is Test:: Printf ()"<< Endl; }};intMain () {singleton<test>:: Getsigleton ()->printf ();return 0;}

Singleton single-Case mode

Related Article

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.