J
John Harrison
Thomas Lorenz said:Hello,
a standard template singleton looks basically like this:
template<class T>
class Singleton1 {
private:
Singleton1();
static Singleton1* m_Instance;
public:
Singleton1& getInstance() {
if (m_Instance == 0) {
m_Instance = new Singleton1();
}
return *m_Instance;
}
};
static Singleton1<T>::m_Instance = 0;
static is not legal here.
This worked fine while used in only one compilation unit, but caused linker
problems. So I came with this variant:
template<class T>
class Singleton2 {
private:
Singleton2();
public:
Singleton2& getInstance() {
static Singleton2 instance;
return instance;
}
};
Compiles fine unit tests are working... but... Usually Singletons are not
implemented that way. Did I overlook something?
Did you put all the code in a header file? Including the definition of
m_Instance? There is no reason that your first version should cause linker
problems if you put all the code in the right places.