@lupnfer
2017-03-06T12:37:51.000000Z
字数 2336
阅读 884
Code
Q(TODO): Args&& ... args 跟 Args& ... args的区别
c++11
/************************************************************************$Id: singleton.h 1963 2016-03-01 12:12:37Z $Product:Project:Created:Authors:Description: common singleton-------------------------------------------------------------------------ChangeLogDATE NAME DESCRIPTION-------------------------------------------------------------------------************************************************************************/#ifndef WISEOS_COMMON_SINGLETON_H_#define WISEOS_COMMON_SINGLETON_H_#include <string>#include <iostream>#include <memory>#include <mutex>namespace wiseos {namespace common {template <typename T>class Singleton {public:template<typename... Args>//static T &GetInstance(Args& ... args) diff c++ primerstatic inline std::shared_ptr<T> instance(Args&& ... args) {// using double-check-lock.if (!instance_.get()) {std::unique_lock<std::mutex> lock(instanceMutex_);if (!instance_.get()) {instance_.reset(new T(std::forward<Args>(args)...));}}return instance_;}private:Singleton() = default;virtual ~Singleton() = default;Singleton(const Singleton&) = default;Singleton& operator = (const Singleton &) = delete;// instancestatic std::shared_ptr<T> instance_;static std::mutex instanceMutex_;};} // namespace common} // namespace wiseostemplate <typename T>std::shared_ptr<T> wiseos::common::Singleton<T>::instance_;template <typename T>std::mutex wiseos::common::Singleton<T>::instanceMutex_;#define SINGLETON_DECL(type) \friend class std::shared_ptr< type >; \friend class wiseos::common::Singleton< type >;#endif // WISEOS_COMMON_SINGLETON_H_
-lboost_thread -boost_system
C++03
#ifndef _SINGLETON_H_#define _SINGLETON_H_#include <string>#include <boost/thread.hpp>using namespace std;template < typename T>class Singleton{public :template<typename... Args>static T &GetInstance(Args& ... args) {// using double-check-lock.if(instance_ == NULL) {boost::unique_lock<boost::mutex> lock(instanceMutex_);if(instance_ == NULL) {instance_ = new T(args ...);atexit(Destroy); //register fun when process exit}}return *instance_;}private :static void Destroy(){delete instance_;instance_ = NULL;}Singleton(const Singleton &other);Singleton & operator = (const Singleton &other);Singleton();~Singleton();static T *instance_;static boost::mutex instanceMutex_;};//static member inittemplate < typename T>T *Singleton<T>::instance_ = NULL;template <typename T>boost::mutex Singleton<T>::instanceMutex_;#endif // _SINGLETON_H_