zoukankan      html  css  js  c++  java
  • 单例模式

    class Singleton  
    {
        public:
            static Singleton& Instance()
        {
            static Singleton instance;
            return instance;
        }
        private:
            Singleton();
            ~Singleton();
            Singleton(const Singleton&);
            Singleton& operator=(const Singleton&);
    };
    

     采用effective c++中的方法,这里用到了static Singleton instance;这是一个local static对象,只有在第一次访问Instance()对象时候才会创建。注意这边将构造和析构函数都设为私有并且只声明,因此编译器不会在需要的时候自动再产生。

    static Singleton& Instance()  
    {
        if (instance_ == NULL) 
        {
            Lock lock; //基于作用域的加锁,超出作用域,自动调用析构函数解锁
            if (instance_ == NULL)
            {
                  instance_ = new Singleton;
            }
        }
        return *instance_;
    }
    

      双锁模式,线程安全。

    via(http://www.zkt.name/dan-li-mo-shi-singleton-ji-c-shi-xian/) 

  • 相关阅读:
    php解析xml文件的方法
    while倒数阶乘的和
    菱形代码
    0929课堂随记
    0929作业
    0928练习作业
    HelloJava
    Java例题
    Hello World(本博客启程篇)
    vue 如何实现在函数中触发路由跳转
  • 原文地址:https://www.cnblogs.com/rockwall/p/5788020.html
Copyright © 2011-2022 走看看