c++单例模式的一种写法

首言

在以前的文章中,我写了一种单例模式。不过那种写法会比较麻烦,要加好几行代码。如今看到了大佬写的新的单例模式,我进行了改进,比较好玩,现在记录下来。

大佬的单例模式

cpp 复制代码
#include <stdexcept>

template <typename T>
class Singleton {
public:
    template<typename... Args>
    static T* Instance( Args&&... args ) {
        if ( m_pInstance == nullptr )
            m_pInstance = new T( std::forward<Args>( args )... );

        return m_pInstance;

    }

    static T* GetInstance( ) {
        if ( m_pInstance == nullptr )
            throw std::logic_error( "the instance is not init, please initialize the instance first" );

        return m_pInstance;
    }

    static void DestroyInstance( ) {
        delete m_pInstance;
        m_pInstance = nullptr;
    }

private:
    static T* m_pInstance;
};

template <class T> T*  Singleton<T>::m_pInstance = nullptr;
cpp 复制代码
#include "Singleton.h"

class Test: public Singleton<Test>
{
public:
    Test(int selfNum):_selfNum(selfNum) {};
    void sayhello(){
    	std::cout<<"hello--"<<_selfNum<<std::endl;
	};
protected:
    int _selfNum = -1;
};

使用时是这样的

cpp 复制代码
	Test one(1);
    Test two(2);
    one.sayhello();
    two.sayhello();
    Singleton<Test>::Instance(3);
    Singleton<Test>::GetInstance()->sayhello();
    Test::Instance(4);
    Test::GetInstance()->sayhello();

打印结果

cpp 复制代码
hello--1
hello--2
hello--3
hello--3

为什么最后两条是一样的数字呢?因为 Test 继承了 Singleton<Test> ,所以最后两种写法是等价的。

这里有一个大问题,假如别人使用这个类,同时忘记需要写成单例模式,就像 Test one(1);一样,那么代码就乱套了,针对这个问题,进行下列改动。

改进后代码

cpp 复制代码
#include "Singleton.h"

class Test: public Singleton<Test>
{
public:
    friend class Singleton;
    
    void sayhello(){
    	std::cout<<"hello--"<<_selfNum<<std::endl;
	};
protected:
    Test(int selfNum):_selfNum(selfNum) {};
    int _selfNum = -1;
};

使用了 friend 关键字,让 Singleton 可以访问 Test 的被保护函数,同时将 Test 的构造函数放入保护段,这样封住了可能出问题的部分。

相关推荐
乄夜20 分钟前
嵌入式面试高频(5)!!!C++语言(嵌入式八股文,嵌入式面经)
c语言·c++·单片机·嵌入式硬件·物联网·面试·职场和发展
YYDS31435 分钟前
C++动态规划-01背包
开发语言·c++·动态规划
wydaicls1 小时前
十一.C++ 类 -- 面向对象思想
开发语言·c++
姜君竹2 小时前
QT的工程文件.pro文件
开发语言·c++·qt·系统架构
思捻如枫2 小时前
C++数据结构和算法代码模板总结——算法部分
数据结构·c++
weixin_478689763 小时前
C++ 对 C 的兼容性
java·c语言·c++
k要开心3 小时前
C++概念以及基础框架语法
开发语言·c++
weixin_307779133 小时前
Linux下GCC和C++实现统计Clickhouse数据仓库指定表中各字段的空值、空字符串或零值比例
linux·运维·c++·数据仓库·clickhouse
秦少游在淮海4 小时前
C++ - string 的使用 #auto #范围for #访问及遍历操作 #容量操作 #修改操作 #其他操作 #非成员函数
开发语言·c++·stl·string·范围for·auto·string 的使用
const5444 小时前
cpp自学 day2(—>运算符)
开发语言·c++