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 的构造函数放入保护段,这样封住了可能出问题的部分。

相关推荐
SccTsAxR19 分钟前
算法基石:手撕离散化、递归与分治
c++·经验分享·笔记·算法
Q741_1471 小时前
每日一题 力扣 3655. 区间乘法查询后的异或 II 模拟 分治 乘法差分法 快速幂 C++ 题解
c++·算法·leetcode·模拟·快速幂·分治·差分法
夏乌_Wx1 小时前
剑指offer | 2.4数据结构相关题目
数据结构·c++·算法·剑指offer·c/c++
米啦啦.1 小时前
C+类的友元与静态成员函数,类模板
c++·友元·类模板
超绝振刀怪1 小时前
【C++可变模板参数】
开发语言·c++·可变模板参数
minji...2 小时前
Linux 线程同步与互斥(二) 线程同步,条件变量,pthread_cond_init/wait/signal/broadcast
linux·运维·开发语言·jvm·数据结构·c++
梓䈑2 小时前
高性能 C++ 日志实战:spdlog 核心架构解析与最佳实践指南
c++·架构
草莓熊Lotso2 小时前
【Linux 线程进阶】进程 vs 线程资源划分 + 线程控制全详解
java·linux·运维·服务器·数据库·c++·mysql
唐樽2 小时前
C++ 竞赛学习路线笔记
c++·笔记·学习
ShineWinsu2 小时前
对于Linux:文件操作以及文件IO的解析
linux·c++·面试·笔试·io·shell·文件操作