Boost logo

Boost :

From: peter.nordlund_at_[hidden]
Date: 2001-11-18 02:03:13


I have a very short Singleton base class that can be used as
Magnus Flodin suggests.

For the interested reader I written a tech report on it.
http://www.nada.kth.se/cvap/abstracts/cvap246.html

template <typename T /* Singleton type */, typename MANAGER>
class Singleton: public noncopyable {
public:
  typedef MANAGER ManagerType;
  typedef T SingletonType;
  inline static T& instance();
  inline static const T& constInstance();
protected:
  Singleton() { };
  ~Singleton() { };
};
// Implementation
//
template <typename T, typename MANAGER>
inline T& Singleton<T, MANAGER>::instance() {
  // The construction below manages both a member template
  // function AND ordinary function, as opposed to the
  // construction MANAGER::instance<T>();
  T* typeArg = 0;
  return MANAGER::instance(typeArg); //>x
}

This class leaves the field open for endlessly amounts of MANAGER
classes.
Examples:
1. I have implemented an exception correct Manager class that destroys
   Singletons in a particular order. The order is then a template
argument
   to the Manager class.
2. As an example, it is quite trivial to wrap up the whole
Alexandrescu's
   "Modern C++ Design" SingletonHolder inside the MANAGER class.
3. I have written a Manager class that fetches data from disk on
instantiation.
4. A Manager class that detects circular instantiations.
5. A very simple code example is provided below.
-------------------------
#include <singleton/managed-singleton.hpp>
#include <iostream>

namespace ManagedSingleton {
  // Here comes a Manager class with no kind of cleanup at program
exit.
  // No double checked locking either.
  struct NoCleanupMgr {
    template <typename T> static T& instance(T*) {
      static T* theInstance = 0;
      if (0 == theInstance) theInstance = new T;
      return *theInstance;
    }
  };
};

class Test1: public ManagedSingleton::Singleton<Test1,
  ManagedSingleton::NoCleanupMgr> {
  friend class ManagedSingleton::NoCleanupMgr;
private:
  ~Test1() throw() { }
  Test1() { std::cerr << "Test1()" << std::endl; }
};

int main(int argc, const char** argv) {
  Test1::instance();
  return 0;
}


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk