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

相关推荐
Je1lyfish1 小时前
CMU15-445 (2025 Fall/2026 Spring) Project#3 - QueryExecution
linux·c语言·开发语言·数据结构·数据库·c++·算法
Brilliantwxx1 小时前
【C++】 vector(代码实现+坑点讲解)
开发语言·c++·笔记·算法
叼烟扛炮2 小时前
C++第三讲:类和对象(中)
开发语言·c++·类和对象
KuaCpp2 小时前
C++新特性学习
c++·学习
墨染千千秋3 小时前
C/C++ Keywords
c语言·c++
ximu_polaris3 小时前
设计模式(C++)-行为型模式-中介者模式
c++·设计模式·中介者模式
CSCN新手听安5 小时前
【Qt】Qt窗口(八)QFontDialog字体对话框,QInputDialog输入对话框的使用,小结
开发语言·c++·qt
tumu_C5 小时前
用std::function减缓C++模板代码膨胀和编译压力的一个场景
开发语言·c++
Hical616 小时前
C++17 实战心得:那些真正改变我写代码方式的特性
c++
Hical617 小时前
实测:C++20 协程 vs Go Gin vs Rust Actix,谁的 Web 性能更强?
c++