赞
踩
免责声明:以下程序仅供自己参考使用,如果有好的编程建议,可以提出,感激不尽
可以考虑最简单的实现方式,利用static特性实现
class SingleModeDemo
{
public:
static SingleModeDemo& Instance()
{
static SingleModeDemo instance;
return instance;
}
private:
SingleModeDemo() {}
SingleModeDemo(const SingleModeDemo&) = delete;
SingleModeDemo& operator=(const SingleModeDemo&) = delete;
};
采用双重锁定检查方式,同时使用c++的atomic模板保证按照设想方式执行程序
/* demo.h */ #pragma once #include <atomic> #include <mutex> class SingleModeDemo { public: static SingleModeDemo& Instance() { SingleModeDemo* inst = m_instance.load(); if (inst == NULL) { std::lock_guard<std::mutex> lock(m_mutex); inst = m_instance.load(); if (inst == NULL) { inst = new SingleModeDemo; m_instance.store(inst); } } return *inst; } private: SingleModeDemo() {} SingleModeDemo(const SingleModeDemo&) = delete; SingleModeDemo& operator=(const SingleModeDemo&) = delete; static std::mutex m_mutex; static std::atomic<SingleModeDemo*> m_instance; };
由于使用到了static的类成员,所以需要在实现中定义成员
/*
demo.cpp
*/
#include "demo.h"
std::mutex SingleModeDemo::m_mutex;
std::atomic<SingleModeDemo*> SingleModeDemo::m_instance;
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。