#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;
}

 

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐