Skip to content

Instantly share code, notes, and snippets.

@wencan
Created January 12, 2015 01:07
Show Gist options
  • Save wencan/e228ddca7b63470132f0 to your computer and use it in GitHub Desktop.
Save wencan/e228ddca7b63470132f0 to your computer and use it in GitHub Desktop.
SingletonOnce
/*
* SingletonOnce.hpp
*
* Created on: Jan 9, 2015
* Author: wencan
*/
#ifndef SINGLETONCALLONCE_HPP_
#define SINGLETONONCE_HPP_
#include <memory>
#include <mutex>
/**
* 单例模板
* 使用C++ 11的call_once保证多线程环境下之后构建对象一次
* 使用共享指针,确保单例对象最后被析构
*
* wencan
* 2015-01-09
*/
template<typename T>
class SingletonOnce
{
//protected:
// SingletonOnce() {};
//public:
// virtual ~SingletonOnce() {};
//private:
// SingletonOnce<T> (const SingletonOnce<T> &){}
// SingletonOnce<T> & operator = (const SingletonOnce<T> &){}
public:
static std::shared_ptr<T> Instance()
{
std::call_once(m_once_flag, [](){SingletonOnce<T>::m_instance.reset(new T());});
return m_instance;
}
private:
static std::shared_ptr<T> m_instance;
static std::once_flag m_once_flag;
};
template<typename T>
std::shared_ptr<T> SingletonOnce<T>::m_instance;
template<typename T>
std::once_flag SingletonOnce<T>::m_once_flag;
#endif /* SINGLETONONCE_HPP_ */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment