singleton.h

00001 /*
00002  * singleton.h
00003  * This file is part of dbPager Classes Library (DCL)
00004  *
00005  * Copyright (c) 2008 Dennis Prochko <wolfsoft@mail.ru>
00006  *
00007  * DCL is free software; you can redistribute it and/or modify
00008  * it under the terms of the GNU General Public License as published by
00009  * the Free Software Foundation version 3.
00010  *
00011  * DCL is distributed in the hope that it will be useful,
00012  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00013  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00014  * GNU General Public License for more details.
00015  *
00016  * You should have received a copy of the GNU General Public License
00017  * along with DCL; if not, write to the Free Software
00018  * Foundation, Inc., 51 Franklin St, Fifth Floor,
00019  * Boston, MA  02110-1301  USA
00020  */
00021 
00022 #ifndef _SINGLETON_H_
00023 #define _SINGLETON_H_
00024 
00025 #include <memory>
00026 
00027 #include <dcl/mutex.h>
00028 #include <dcl/noncopyable.h>
00029 
00030 namespace dbp {
00031 
00033 
00051 template <class T>
00052 class singleton: public noncopyable {
00053 public:
00055 
00061         static T& instance() {
00062                 if (!_instance.get()) {
00063                         mutex_guard m(_cs);
00064                         if (!_instance.get())
00065                                 _instance.reset(new T());
00066                         else
00067                                 _instance->_is_copy = true;
00068                 } else
00069                         _instance->_is_copy = true;
00070                 return *_instance;
00071         };
00073 
00079         bool is_copy() {
00080                 return _is_copy;
00081         };
00082 protected:
00083         singleton(): _is_copy(false) { };
00084 private:
00085         bool _is_copy;
00086         static std::auto_ptr<T> _instance;
00087         static mutex _cs;
00088 };
00089 
00090 template <class T>
00091 std::auto_ptr<T> singleton<T>::_instance;
00092 
00093 template <class T>
00094 mutex singleton<T>::_cs;
00095 
00096 } //namespace
00097 
00098 #endif /*_SINGLETON_H_*/

 
Support This Project
SourceForge.net Logo