C + + Simple Object release

Source: Internet
Author: User
C single-mode (thread-safe, memory-free)Itdadao 2016-08-09 08:53:06 Technology 27 ℃ No comment

Lazy mode: That is, the first time the class instance is invoked, a new instance of that class is generated, and only this instance is returned at a later time.
Locks are required to ensure thread safety: Reason: Multiple threads may enter an If statement that determines whether an instance already exists, thereby non thread safety.
Use double-check to ensure thread safety. However, if a large amount of data is processed, the lock becomes a serious performance bottleneck.
1, static member instances of the lazy mode:

Class Singleton  
{  
private:  
    static singleton* m_instance;  
    Singleton () {} public  
:  
    static singleton* getinstance ();  

singleton* singleton::getinstance ()  
{  
   if (NULL = = m_instance)  
   {  
       Lock ();//Borrow other classes to implement, such as boost  
       if (NULL = = m_instance)  
       {  
           m_instance = new Singleton;  
       }  
       UnLock ();  
   }  
   return m_instance;  

2, internal static instances of the lazy model
It should be noted here that after c++0x, the compiler is required to guarantee the thread safety of internal static variables, without locking. But before C + + 0X, you still need to lock.

Class Singletoninside  
{  
private:  
    singletoninside () {} public  
:  
    static singletoninside* getinstance ()  
    {  
        Lock ();//not needed after c++0x  
        static singletoninside instance;  
        UnLock (); Not needed after c++0x return  
        instance;   
    }  
;  

Second, a hungry man mode: that is, whether or not an instance of the class is invoked, an instance of the class is generated at the beginning of the program, and only this instance is returned at a later time.
The static initialization instance guarantees its thread security, WHY. Because the static instance initialization is initialized by the main thread in a single-threaded manner before the program begins to enter the main function, there is no need to worry about multithreaded issues.
Therefore, in the performance demand is high, should use this mode, avoid frequent lock contention.

Class Singletonstatic  
{  
private:  
    static const singletonstatic* m_instance;  
    Singletonstatic () {} public  
:  
    static singletonstatic* getinstance ()  
    {return  
        m_instance;  
    }  
};  

External initialization before invoke main  
const singletonstatic* singletonstatic::m_instance = new Singletonstatic;  

when will the m_pinstance point of space be released? A more serious problem is when the destructor of the instance executes.

If there are necessary actions in the destructor of the class, such as closing the file and releasing the external resources, the above code cannot implement this requirement. We need a way to normally delete the instance.
You can call getinstance () at the end of the program and drop the delete action on the returned pointer. This can achieve functionality, but not only ugly, but also error prone. Because such additional code is easily forgotten, it is also difficult to guarantee that after the delete, no code calls the GetInstance function.
A good way to do this is to let the class know that it will delete itself at the right time, or to hang its own operation at a suitable point in the operating system so that it is automatically executed at the right time.
We know that at the end of the program, all global variables are automatically destructor. In fact, the system also destructors the static member variables of all classes, just as these static members are global variables. With this feature, we can define a static member variable in a singleton class, and its only job is to delete an instance of a singleton class in the destructor. As in the following code, the Cgarbo class (Garbo means garbage worker):

Class Csingleton  
{  
//other member public  
:  
    static csingleton* getinstance ();  
Private:  
    Csingleton () {};  
    Static Csingleton * m_pinstance;  
    Class Cgarbo//Its only job is to delete the Csingleton instance in the destructor {public  
    :  
        ~cgarbo ()  
        {  
            if (csingleton::m_ pinstance)  
                Delete csingleton::m_pinstance  
        }  
    Static Cgabor Garbo; Define a static member, the system will automatically call its destructor when the program ends  
;  

A class Cgarbo is defined as a private inline class of Csingleton in case the class is abused elsewhere.
At the end of the program, the system calls the Csingleton static member Garbo, which deletes a single instance of the singleton.
Freeing a single Instance object with this method has the following characteristics:
Defining a proprietary nested class within a single instance class;
Defines a private, static member in a single class that is specifically for release;
At the end of the program, the characteristics of global variables are reconstructed and the final release time is chosen.
Code that uses a single example does not require any action and does not care about the release of the object.
The specific code is as follows:

#include <iostream>> using namespace std;  
Class Singleton {public:static Singleton *getinstance ();  
    Private:singleton () {cout << "Singleton ctor" << Endl;  
    } ~singleton () {cout << "Singleton dtor" << Endl;  
    Static Singleton *m_pinstance;   
                Class Garbo {public: ~garbo () {if (singleton::m_pinstance) {  
                cout << "Garbo dtor" << Endl;  
            Delete singleton::m_pinstance;  
    }  
        }  
    };  
Static Garbo Garbo;   
};  Singleton::garbo Singleton::garbo;  
Be sure to initialize, otherwise the program will not be destructor at the end of garbo Singleton *singleton::m_pinstance = NULL;  
    Singleton *singleton::getinstance () {if (m_pinstance = NULL) m_pinstance = new Singleton;  
return m_pinstance;  
    int main () {Singleton *p1 = singleton::getinstance (); Singleton *P2 = Singleton::getinstance ();  
    if (P1 = = p2) cout << "P1 = = p2" << Endl;  
return 0;  }
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.