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

    单例模式的意图:保证一个类只有一个实例,并提供一个访问它的全局访问点。
    以下两种方法没有考虑线程安全问题,如需应用在多线程环境下,需要加锁。

    第一种形式:实现通过返回一个引用实现单例模式。如果返回的是一个指针而不是一个引用,用户可能会不小心删除此指针,因此上述实现比返回指针更安全。'

    class Singleton{
        static Singleton s;
        int i;
        Singleton(int x) : i(x){};
        Singleton & operator=(Singleton&); // 不允许赋值
        Singleton(const Singleton&); // 不允许拷贝
    public:
        static Singleton& instance() {return s;}
        int getValue() {return i;}
        void setValue(int x) {i = x;}
    };
    
    int main()
    {
        Singleton& s = Singleton::instance();
        cout << s.getValue() << endl;
        Singleton & s2 = Singleton::instance();
        s2.setValue(9);
        cout << s.getValue() << endl;
        return 0;
    }
    

    第二种形式:通过成员函数内部的静态对象的创建实现单例模式。

    class Singleton{
        int i;
        Singleton(int x) : i(x){};
        void operator=(Singleton&);
        Singleton(const Singleton&);
    public:
        static Singleton & instance()
        {
            static Singleton s(47);
            return s;
        }
        int getValue() {return i;}
        void setValue(int x){i = x;}
    };
    
    int main()
    {
        Singleton& s = Singleton::instance();
        cout << s.getValue() << endl;
        Singleton& s2 = Singleton::instance();
        s2.setValue(9);
        cout << s.getValue() << endl;
        return 0;
    }
    
  • 相关阅读:
    JVM基础
    JVM基础
    python相关
    charles 的配置与使用
    大型缓存架构实战
    redis环境搭建
    多线程与并发 | 线程池
    JVM | 内存溢出和解决方案
    读书笔记 | Mysql是怎样运行的
    读书笔记 | Java并发编程实战
  • 原文地址:https://www.cnblogs.com/myblog1993/p/11440709.html
Copyright © 2011-2022 走看看