degate  0.1.2
SingletonBase.h
Go to the documentation of this file.
00001 /* -*-c++-*-
00002 
00003  This file is part of the IC reverse engineering tool degate.
00004 
00005  Copyright 2008, 2009, 2010 by Martin Schobert
00006 
00007  Degate 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, either version 3 of the License, or
00010  any later version.
00011 
00012  Degate is distributed in the hope that it will be useful,
00013  but WITHOUT ANY WARRANTY; without even the implied warranty of
00014  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00015  GNU General Public License for more details.
00016 
00017  You should have received a copy of the GNU General Public License
00018  along with degate. If not, see <http://www.gnu.org/licenses/>.
00019 
00020 */
00021 
00022 #ifndef __SINGLETONBASE_H__
00023 #define __SINGLETONBASE_H__
00024 
00025 
00026 #include <boost/utility.hpp>
00027 #include <boost/thread/once.hpp>
00028 #include <boost/scoped_ptr.hpp>
00029 
00030 
00031 namespace degate {
00032 
00033   /**
00034    * This is a base class for singletons.
00035    */
00036 
00037   template<class T>
00038   class SingletonBase : private boost::noncopyable {
00039 
00040   private:
00041     static boost::scoped_ptr<T> t;
00042     static boost::once_flag flag;
00043 
00044   protected:
00045 
00046     /**
00047      * Constructor.
00048      */
00049 
00050     SingletonBase() {}
00051 
00052     /**
00053      * Destructor.
00054      */
00055 
00056     virtual ~SingletonBase() {}
00057 
00058   public:
00059 
00060     /**
00061      * Get a reference to the singleton.
00062      */
00063 
00064     static T & get_instance() {
00065       boost::call_once(init, flag);
00066       return *t;
00067     }
00068 
00069     /**
00070      * Initialize the singleton.
00071      */
00072 
00073     static void init() {
00074       t.reset(new T());
00075     }
00076 
00077   };
00078 
00079   template<class T> boost::scoped_ptr<T> SingletonBase<T>::t(0);
00080   template<class T> boost::once_flag SingletonBase<T>::flag = BOOST_ONCE_INIT;
00081 
00082 
00083 }
00084 
00085 #endif