zoukankan      html  css  js  c++  java
  • Singleton单例模式--C++实现

    1. 只支持单线程 (不推荐)

     1 #include <iostream>
     2 using namespace std;
     3 
     4 class Singleton
     5 {
     6 public:
     7     static Singleton* getInstance();//<1>必须是static,这样才可以通过类名访问。
     8 private:
     9     static Singleton* _instance;//<2>必须是static,这样生存期才是全局的。
    10     Singleton();//<3>必须是private,这样就不能通过构造函数来实例化。
    11 };
    12 
    13 Singleton* Singleton::getInstance()
    14 {
    15     if (_instance == NULL)
    16     {
    17         _instance = new Singleton();
    18     }
    19     return _instance;
    20 }
    21 Singleton* Singleton::_instance = NULL;//static变量必须初始化
    22 Singleton::Singleton()    //构造函数既然要用到,而且类内部也声明了,就必须给出定义才能用。
    23 {
    24     cout << "success" << endl;
    25 }
    26 
    27 int main()
    28 {
    29     Singleton* sgt = Singleton::getInstance();
    30 }
    View Code

    reference[1]将代码分成了Singleton.h, Singleton.cpp和main.cpp三个文件来实现,回顾一下文件组织。

    2. 多线程 (通用)

     1 class Singleton
     2 {
     3 public:
     4     static Singleton* GetInstance()
     5     {
     6         static Singleton instance;
     7         return &instance;
     8     }
     9 
    10 private:
    11     Singleton() {}                              // ctor hidden
    12     Singleton(const Singleton& s);            // copy ctor hidden
    13     Singleton& operator=(const Singleton& s); // assign op. hidden
    14 };

    C++11后使用static是线程安全的。

    “If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization.”

    当一个线程正在初始化一个变量的时候,其他线程必须得等到该初始化完成以后才能访问它。

     不想让一个类被隐式或显式地构造,就把它的构造函数和big three(拷贝构造函数,重载赋值运算符,析构函数)给定义成private并且只声明不实现。这样别人就没法来用了。

    否则的话,编译器会自动为它生成构造函数和big three。

    reference:

    [1] http://ccftp.scu.edu.cn:8090/Download/038c70a8-c724-4b86-91c3-74b927b1d492.pdf

    [2] http://www.cnblogs.com/bigwangdi/p/3139831.html

    [3] http://liyuanlife.com/blog/2015/01/31/thread-safe-singleton-in-cxx/

    [4] http://blog.sina.com.cn/s/blog_6ce9e8870101i1cz.html

    [5] http://wuchong.me/blog/2014/08/28/how-to-correctly-write-singleton-pattern/#

    [6] http://blog.csdn.net/crayondeng/article/details/24853471

    [7] http://www.aristeia.com/Papers/DDJ_Jul_Aug_2004_revised.pdf

    [8] http://blog.csdn.net/dragoncheng/article/details/2781#t4

  • 相关阅读:
    openjump遇到的一些问题
    kettle安装教程/安装失败
    C# string和byte[]数组之间相互转换
    C# 各种进制转换
    C#AE创建FeatureDataset/创建数据、集要素集
    ArcCatalog/arcgis怎么连接postgresql/postpis
    梦断代码阅读笔记03
    体温冲刺完成
    体温冲刺
    体温作业
  • 原文地址:https://www.cnblogs.com/forcheryl/p/4550321.html
Copyright © 2011-2022 走看看