C ++ Singleton Mode

Source: Internet
Author: User

In the design pattern of gof, a class is guaranteed to have only one instance and a global access point is provided. Generally, we can make a global variable to make an object accessible, but it cannot prevent you from instantiating multiple objects. The best way is to let the class itself be responsible for saving its unique instance. This class can ensure that no other instance can be created, and it can provide a method to access the instance.

In other words, we often need global objects. For example, in a project, there is only one database access object. In this case, we can consider using the singleton mode. The Singleton mode is better than the global object. The Singleton class can be inherited, as shown in the following example.

The key aspect of the singleton mode is the private and static getinstance of the constructor.

In addition, pay attention to the memory release in C ++. In C ++, Java, and C #, pay attention to the synchronization problem when multithreading occurs.

# Include <iostream. h> Class  Csingleton {  Public  :  Static Csingleton * Getinstance (){  If (Null = M_pinstance) m_pinstance =New  Csingleton ();  Return  M_pinstance ;}  Static   Void Release () //  Required. Otherwise, memory leakage may occur.  {  If (Null! = M_pinstance) {Delete m_pinstance; m_pinstance = NULL ;}}  Protected : Csingleton () {cout < "  Csingleton  " < Endl ;};  Static Csingleton * M_pinstance;}; csingleton * Csingleton: m_pinstance = NULL;

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.