C++实现单例模式

"懒汉模式",注意多线程时可能多次构造,这里使用两次判断加锁解决。

cpp 复制代码
#include <iostream>
#include <mutex>

std::mutex g_mutex;		

class testA {
public:
	static testA* GetInstance() {
		if (singleton == nullptr)
		{
			std::unique_lock<std::mutex> lock(g_mutex);			//RAII自动上锁解锁
			if (singleton == nullptr)
			{
				singleton = new testA();
			}
		}

		return singleton;
	}

private:
	testA() {
		std::cout << "进行构造函数使用" << std::endl;
	};
	static testA* singleton;
};

//初始化成员变量
testA* testA::singleton = nullptr;

int main()
{

	testA* a = testA::GetInstance();

	testA* b = testA::GetInstance();

	return 0;
}

饿汉模式,类声明即初始化,无线程安全问题

cpp 复制代码
#include <iostream>

class testA {
public:
	static testA* GetInstance() {
		
		return singleton;
	}

private:
	testA() {
		std::cout << "进行构造函数使用" << std::endl;
	};
	static testA* singleton;
};

//初始化成员变量
testA* testA::singleton = new testA();

int main()
{

	testA* a = testA::GetInstance();

	testA* b = testA::GetInstance();

	return 0;
}

实现原理为在私有成员函数中声明类的构造函数,这样默认构造函数就不会有了。然后将其设置为static静态成员变量,可使用类::函数名称方式直接调用。饿汉模式为类声明好之后直接初始化,懒汉模式为用的时候判断是否为空指针,如果为空指针则声明。

相关推荐
独隅26 分钟前
CLion 接入 Codex 的完整配置使用全面指南
c++·ide·ai·c++23
老洋葱Mr_Onion44 分钟前
【C++】高精度模板
开发语言·c++·算法
我不是懒洋洋2 小时前
从零实现一个分布式计算:MapReduce的核心设计
c++
小王C语言12 小时前
【7. 实现登录注册模块】:实现会话管理、注册/登录/退出 API
网络·c++
峥无14 小时前
C++11 深度详解:现代 C++ 基石全梳理
开发语言·c++·笔记
阿米亚波15 小时前
【C++ STL】std::unordered_multimap
开发语言·数据结构·c++·笔记·stl
小王C语言15 小时前
【3. 基于 Vibe Coding 的 OJ 平台】. 构建仓库、环境准备、需求梳理、安装依赖
网络·c++
小王C语言16 小时前
【8.进行接口测试】:通过 curl 进行接口自动化测试 / 通过 python 程序进行接口自动化测试
网络·c++
888CC++17 小时前
C++ 快速学习指南:从入门到进阶的实战路线
开发语言·c++
小小晓.17 小时前
C++记:函数
开发语言·c++·算法