• C++实现单例模式


    单线程:

    class Singleton
    {
    private:
        static Singleton* _instance;
        Singleton()
        {
    
        }
    public:
        static Singleton* Instance()
        {
            if (nullptr == _instance)
                _instance = new Singleton();
            return _instance;
        }
        static void DestoryInstance()
        {
            if (nullptr != _instance)
            {
                delete _instance;
                _instance = nullptr;
            }
        }
        void fun()
        {
            cout << "fun" << endl;
        }
    };
    
    Singleton* Singleton::_instance = nullptr;

    C++11多线程:

    class Singleton
    {
    private:
        Singleton()
        {
    
        }
    public:
        static Singleton* Instance()
        {
            static Singleton m_instance;
            return &m_instance;
        }
    
        void fun()
        {
            cout << "fun" << endl;
        }
    };

    注:C++11标准才支持线程安全的局部静态变量初始化。
    C++memory model中定义static local variable:The initialization of such a variable is defined to occur the first time control passes through its declaration; for multiple threads calling the function, this means there’s the potential for a race condition to define first.

    C++11另一种方式:

    class Singleton
    {
    private:
        static Singleton* _instance;
        static once_flag flag;
    
        Singleton()
        {
    
        }
    public:
        static Singleton* Instance()
        {
            call_once(flag, []() { _instance = new Singleton();});
            return _instance;
        }
    
        void fun()
        {
            cout << "fun" << endl;
        }
    };
    
    Singleton* Singleton::_instance = nullptr;
    once_flag Singleton::flag;
    
    
    
    int main()
    {
        vector<thread> vt;
        for (int i = 0; i < 100; ++i)
        {
            vt.push_back(thread([]() {
                Singleton* single = Singleton::Instance();
                single->fun();
            }));
        }
        for_each(vt.begin(), vt.end(), mem_fn(&thread::join));
    
        system("pause");
        return 0;
    }
  • 相关阅读:
    互联网协议入门(一)(转)
    程序员的自我修养——操作系统篇(转)
    程序员的自我修养(2)——计算机网络(转)
    里氏替换原则
    Windows Phone 自学笔记 : ApplicationBar
    如何写好代码
    C# 通过操作注册表控制系统 (更新)
    优秀PPT 设计的十大秘诀
    设计模式学习--面向对象的5条设计原则
    SOLID (面向对象设计) From 维基百科
  • 原文地址:https://www.cnblogs.com/ggzone/p/5094527.html
Copyright © 2020-2023  润新知