Is this safe?
I have come across a singleton implementation of the following form in
some code I have to maintain...
file - Singleton.h
#ifndef SINGLETON_H
#define SINGLETON_H
template<class T>
{
public:
static T& instance()
{
if ( !instance_ )
{
AccessLock<CriticalSection> access(key_);
if ( !instance_ )
{
static Singleton<T> theInstance;
instance_ = &theInstance;
}
}
return instance_;
}
protected:
Singleton() : object_() {}
~Singleton() {}
private:
Singleton(const Singleton&);
Singleton<T>& operator=( const Singleton<T>& );
T object_;
static Singleton<T>* instance_;
static CriticalSection key_;
};
template<typename T>
static Singleton<T>* Singleton<T>::instance_ = 0;
template<typename T>
CriticalSection PhoenixSingleton<T>::key_;
#endif // SINGLETON_H
Usage follows the following form for example...
class A
{
friend class Singleton<A>;
public:
int a;
};
.... where the singleton class is intended to give class A singleton
functionality. Singleton objects are then accessed as you'd expect...
A::instance().a = 10;
This all seems to work fine up to a point. What concerns me is that I
can see no specific declarations of instance pointers or critical
section keys for any of the singleton classes in use (and there are
several), beyond these lines in the header file...
template<typename T>
static Singleton<T>* Singleton<T>::instance_ = 0;
template<typename T>
CriticalSection PhoenixSingleton<T>::key_;
Is this safe? Should there be individual declarations of these
statics for each singleton implemented? eg.
static Singleton<A>* Singleton<A>::instance_ = 0;
CriticalSection Singleton<A>::key_;
I see odd crashes on exit where two of the classes are trying to free
std::lists in their destructors. These lists are both inherited from
the same base class. So far as I can tell when one of the lists is
destroyed it list head node pointer has been already been set to 0.
Maybe when the other singleton was destroyed? Is this because each of
the instance pointers is essentially the same? If this is the case
how does this work at all?
Cheers,
Matt.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]