相关文章推荐
道上混的消炎药  ·  南方周末·  1 年前    · 
坚强的领结  ·  基于判别性样本选择的无监督领域自适应方法·  1 年前    · 
直爽的饭盒  ·  易经(华夏上古三大奇书之一)_搜狗百科·  2 年前    · 
爱旅游的山楂  ·  河南方言发一波,你熟悉么、亲切么? - 知乎·  2 年前    · 
越狱的泡面  ·  “这座城市总在为我打开大门” ...·  2 年前    · 
Code  ›  这才是现代C++单例模式简单又安全的实现开发者社区
test delete static 单例模式
https://cloud.tencent.com/developer/article/1695598
欢乐的篮球
2 年前
作者头像
编程珠玑
0 篇文章

这才是现代C++单例模式简单又安全的实现

前往专栏
腾讯云
备案 控制台
开发者社区
学习
实践
活动
专区
工具
TVP
文章/答案/技术大牛
写文章
社区首页 > 专栏 > 编程珠玑 > 正文

这才是现代C++单例模式简单又安全的实现

发布 于 2020-09-10 18:09:51
2K 0
举报

来源:公众号【编程珠玑】

作者:守望先生

ID:shouwangxiansheng

前言

说到单例模式,很多人可能都已经很熟悉了,这也是面试常问的一个问题。对于单线程而言,单例的实现非常简单,而要写出一个线程安全的单例模式,曾经有很多种写法。有兴趣的可以参考这篇文章《 单例模式很简单?但是你真的能写对吗? 》

简单实现

该文章中也提到,由于C++11及以后的版本中,默认静态变量初始化是线程安全的。

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.

写法如下:

//来源:公众号编程珠玑
//作者:守望先生
class Singleton{
public:
    static Singleton& getInstance(){
        static Singleton m_instance;  //局部静态变量
        return m_instance;
    Singleton(const Singleton& other) = delete;
    Singleton& operator=(const Singleton& other) = delete;
protected:
    Singleton() = default;
    ~Singleton() = default;

这里需要注意将其他构造函数设置为delete。避免对象被再次构造或者拷贝。

这种单例被称为Meyers' Singleton。

通用化

当然为了避免给每个对象都单独写个单例,也可以利用模板。

template<typename T>
class Singleton
public:
    static T& getInstance() {
        static T t;
        return t;
    Singleton(const Singleton&) = delete; 
    Singleton& operator=(const Singleton&) = delete; 
protected:
    Singleton() = default;
    ~Singleton() = default;

示例

举个简单的例子来看下吧:

//来源:公众号编程珠玑
//作者:守望先生
#include<iostream>
template<typename T>
class Singleton
public:
    static T& getInstance() {
        static T t;
        return t;
    Singleton(const Singleton&) = delete; 
    Singleton& operator=(const Singleton&) = delete; 
protected:
    Singleton() = default;
    ~Singleton() = default;
class Test:public Singleton<Test>
public:
    void myprint()
        std::cout<<"test Singleton"<<std::endl;
int main()
    Test::getInstance().myprint();
    return 0;

编译运行:

$ g++ -o test test.cc -std=c++11
$ ./test
test Singleton

另一种用法

当然你也可以像下面这样使用:

class Test
public:
    void myprint()
        std::cout<<"test Singleton"<<std::endl;
 
推荐文章
道上混的消炎药  ·  南方周末
1 年前
坚强的领结  ·  基于判别性样本选择的无监督领域自适应方法
1 年前
直爽的饭盒  ·  易经(华夏上古三大奇书之一)_搜狗百科
2 年前
爱旅游的山楂  ·  河南方言发一波,你熟悉么、亲切么? - 知乎
2 年前
越狱的泡面  ·  “这座城市总在为我打开大门” 小镇青年阎志来汉寻梦24年-新华网
2 年前
今天看啥   ·   Py中国   ·   codingpro   ·   小百科   ·   link之家   ·   卧龙AI搜索
删除内容请联系邮箱 2879853325@qq.com
Code - 代码工具平台
© 2024 ~ 沪ICP备11025650号