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

相关推荐
相偎16 分钟前
用观察者模式通知UI刷新数据
c++
CoderCodingNo33 分钟前
【GESP】C++四级真题 luogu-B4040 [GESP202409 四级] 黑白方块
开发语言·c++
小欣加油1 小时前
leetcode 143 重排链表
数据结构·c++·算法·leetcode·链表
给大佬递杯卡布奇诺2 小时前
FFmpeg 基本API avio_open函数内部调用流程分析
c++·ffmpeg·音视频
Cult Of2 小时前
单例模式与线程池的实际应用
单例模式
YuanlongWang2 小时前
C# 设计模式——单例模式
单例模式·设计模式·c#
爱吃生蚝的于勒2 小时前
【Linux】深入理解进程(一)
java·linux·运维·服务器·数据结构·c++·蓝桥杯
chuyanghong2 小时前
Ubuntu下VIM安装及配置
c++
boss-dog3 小时前
崩溃信息追溯——backward-cpp
c++·debug·backward-cpp
Hankin_Liu的技术研究室3 小时前
深入理解 C++ happens-before:高级并发程序员的必修课
c++