"Go" C + + Singleton mode

Source: Internet
Author: User

http://blog.csdn.net/hackbuteer1/article/details/7460019

For thread safety and exception security, the following extensions can be made

  1. Class Lock
  2. {
  3. Private
  4. CCriticalSection M_cs;
  5. Public
  6. Lock (CCriticalSection CS): M_cs (CS)
  7. {
  8. M_cs. Lock ();
  9. }
  10. ~lock ()
  11. {
  12. M_cs. Unlock ();
  13. }
  14. };
  15. Class Singleton
  16. {
  17. Private
  18. Singleton ();
  19. Singleton (const Singleton &);
  20. singleton& operator = (const Singleton &);
  21. Public
  22. static Singleton *instantialize ();
  23. static Singleton *pinstance;
  24. Static CCriticalSection CS;
  25. };
  26. singleton* Singleton::p instance = 0;
  27. singleton* singleton::instantialize ()
  28. {
  29. if (pinstance = = NULL)
  30. { //double check
  31. Lock Lock (CS); //Use lock for thread safety and resource management classes for exception security
  32. //Using the Resource management class, when an exception is thrown, the resource management class object is destroyed, and the destructor always occurs whether the exception is thrown or the statement block ends.
  33. if (pinstance = = NULL)
  34. {
  35. Pinstance = new Singleton ();
  36. }
  37. } ---//my Note: The Lock class here is a local variable, which is then refactored, which will be unlocked.
  38. return pinstance;
  39. }

"Go" C + + Singleton mode

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.