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 分钟前
蓝桥杯 C/C++ 组历届真题合集速刷(一)
c语言·c++·算法·蓝桥杯
努力学习的小廉2 小时前
【智能指针】—— 我与C++的不解之缘(三十三)
开发语言·c++
baobao17676408302 小时前
C++单例模式
javascript·c++·单例模式
shenxiaolong_code3 小时前
编译器bug ?
c++·bug·meta programming·compiler bug
dami_king3 小时前
用C++手搓一个贪吃蛇?
c++·游戏·c
安於宿命4 小时前
【Linux】用C++实现UDP通信:详解socket编程流程
linux·c++·udp
愚润求学5 小时前
【C++】list模拟实现
开发语言·数据结构·c++·list
刚入门的大一新生9 小时前
C++初阶-C++的讲解1
开发语言·c++
ALex_zry12 小时前
C++17模板编程与if constexpr深度解析
开发语言·c++·性能优化
旧时光林13 小时前
P10905 [蓝桥杯 2024 省 C] 回文字符串
c语言·c++·蓝桥杯·模拟·枚举