欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 产业 > C++实现单例模式

C++实现单例模式

2025/5/10 21:59:37 来源:https://blog.csdn.net/weixin_45778713/article/details/144165758  浏览:    关键词:C++实现单例模式

"懒汉模式",注意多线程时可能多次构造,这里使用两次判断加锁解决。

#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;
}

饿汉模式,类声明即初始化,无线程安全问题

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

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词