flyfish 2014-12-16
编写一个Singleton类
class Singleton(){}; 该类是空类经过编译器处理后,C++编译器默认编写的函数代码如下
class Singleton() { public: Singleton() {} // 1 构造函数 Singleton(const Singleton& s{} // 2 拷贝构造函数 ~Singleton(){} // 3 析构函数 Singleton& operator=(const Singleton& s{} // 4 拷贝赋值函数 copy assignment };
2 用户可以调用
利用public成员函数来进行访问
class Singleton { public: static Singleton& getInstance() { static Singleton instance; return instance; } private: Singleton() {}; Singleton(Singleton const&); void operator=(Singleton const&); };编译器不支持C++11,可以参考Boost的实现
class noncopyable { protected: noncopyable() {} ~noncopyable() {} private: noncopyable( const noncopyable& ); noncopyable& operator=( const noncopyable& ); }; typedef noncopyable_::noncopyable noncopyable; class singleton_module : public boost::noncopyable { private: static bool & get_lock(){ static bool lock = false; return lock; } public: static void lock(){ get_lock() = true; } static void unlock(){ get_lock() = false; } static bool is_locked() { return get_lock(); } }; template<class T> class singleton_wrapper : public T { public: static bool m_is_destroyed; ~singleton_wrapper(){ m_is_destroyed = true; } }; template<class T> bool detail::singleton_wrapper< T >::m_is_destroyed = false; template <class T> class singleton : public singleton_module { private: static T & instance; static void use(T const &) {} static T & get_instance() { static detail::singleton_wrapper< T > t; BOOST_ASSERT(! detail::singleton_wrapper< T >::m_is_destroyed); use(instance); return static_cast<T &>(t); } public: static T & get_mutable_instance(){ BOOST_ASSERT(! is_locked()); return get_instance(); } static const T & get_const_instance(){ return get_instance(); } static bool is_destroyed(){ return detail::singleton_wrapper< T >::m_is_destroyed; } }; template<class T> T & singleton< T >::instance = singleton< T >::get_instance();
原文地址:http://blog.csdn.net/flyfish1986/article/details/41967387