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静态成员变量,可使用类::函数名称方式直接调用。饿汉模式为类声明好之后直接初始化,懒汉模式为用的时候判断是否为空指针,如果为空指针则声明。

相关推荐
XY_墨莲伊6 分钟前
【编译原理】实验二:基于有穷自动机FA词法分析器设计与实现
c语言·开发语言·c++·python
小辉同志7 分钟前
74. 搜索二维矩阵
c++·leetcode·矩阵·二分查找
fpcc22 分钟前
信号处理与AI中的卷积的关系
c++·人工智能·信号处理
t***5441 小时前
能否给出更多现代C++设计模式的示例
开发语言·c++·设计模式
梵尔纳多1 小时前
OpenGL 骨骼动画
c++·图形渲染·opengl
智者知已应修善业2 小时前
【51单片机独立按键控制往复流水灯启停】2023-6-13
c++·经验分享·笔记·算法·51单片机
t***5442 小时前
这些设计模式在现代C++中如何应用
java·c++·设计模式
t***5442 小时前
能否给出更多现代C++架构设计模式?
java·开发语言·c++
mjhcsp2 小时前
C++信息论超详解析
开发语言·c++
此生只爱蛋2 小时前
【CAD】Parasolid:CAD的os
c++