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

相关推荐
派阿喵搞电子4 小时前
在UI界面内修改了对象名,在#include “ui_mainwindow.h“没更新
c++·qt·ubuntu·ui
C++ 老炮儿的技术栈5 小时前
UDP 与 TCP 的区别是什么?
开发语言·c++·windows·算法·visual studio
mochensage7 小时前
CSP信奥赛C++常用系统函数汇总
c++·信奥
mochensage7 小时前
C++信息学竞赛中常用函数的一般用法
java·c++·算法
fpcc7 小时前
跟我学c++中级篇——多线程中的文件处理
c++
5:008 小时前
云备份项目
linux·开发语言·c++
乄夜8 小时前
嵌入式面试高频(5)!!!C++语言(嵌入式八股文,嵌入式面经)
c语言·c++·单片机·嵌入式硬件·物联网·面试·职场和发展
YYDS3149 小时前
C++动态规划-01背包
开发语言·c++·动态规划
wydaicls9 小时前
十一.C++ 类 -- 面向对象思想
开发语言·c++
姜君竹10 小时前
QT的工程文件.pro文件
开发语言·c++·qt·系统架构