單例模式以及垃圾回收

#include <iostream>
#include <mutex>
using namespace std;
 
mutex *m_mutex;
 
class Sington
{
private:
    Sington() 
    { 
        cout << "Sington()" << endl; 
        static GarbageCollection g; 
    }
public:
    static Sington* p;
    static Sington* getinstance()
    {
        if(p == NULL)
        {
            m_mutex->lock();
            if(p == NULL)
            {
                p = new Sington();
            }
            m_mutex->unlock();
        }
        return p;
    }
    ~Sington() { cout << "~Sington()" << endl; }
    class GarbageCollection
    {
    public:
        ~GarbageCollection()
        {
            if(Sington::p != NULL)
            {
                cout << hex << "delete p at " << p << endl;
                delete Sington::p;
                Sington::p = NULL;
            }
        }
    };
};
 
Sington* Sington::p = NULL;
 
int main()
{
    Sington* sgt1 = Sington::getinstance();
    Sington* sgt2 = Sington::getinstance();
    cout << hex << "sgt1=" << sgt1 << " sgt2=" << sgt2 << endl;
 
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章