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

相关推荐
coderxiaohan1 天前
【C++】map和set的使用
开发语言·c++
曼巴UE51 天前
UE5 C++ TSet 创建初始和迭代
java·c++·ue5
xrn19971 天前
Android OpenCV SDK 编译教程(WSL2 Ubuntu 22.04 环境)
android·c++·opencv
AA陈超1 天前
Lyra学习5:GameFeatureAction分析
c++·笔记·学习·ue5·lyra
curry____3031 天前
study in Dev-c++(string insert基本用法)(2025.12.2)
c++·string·insert
nono牛1 天前
C++ 语言全面教程 (基础入门)
java·jvm·c++
小年糕是糕手1 天前
【C++同步练习】类和对象(一)
java·开发语言·javascript·数据结构·c++·算法·排序算法
txxzjmzlh1 天前
类和对象(下)
开发语言·c++
运维小文1 天前
Centos7部署.net8和升级libstdc++
开发语言·c++·.net
小年糕是糕手1 天前
【C++同步练习】类和对象(二)
java·开发语言·javascript·数据结构·c++·算法·ecmascript