<分区>
我编写了一个非常简单的程序来实现一个通用的 Singleton 类,如下所示:
namespace core
{
template <typename T>
class Singleton
{
protected:
Singleton(void);
Singleton(Singleton const &other);
virtual ~Singleton(void);
public:
Singleton &operator=(Singleton const &other);
static T *GetSingletonPtr(void);
static T &GetSingleton(void);
static void DestroySingleton(void);
private:
static T *m_pInstance;
static T m_Instance;
};
//Globals initialization
template <typename T>
T *Singleton<T>::m_pInstance = NULL;
template <typename T>
T Singleton<T>::m_Instance = T();
//Initialization
template <typename T>
Singleton<T>::Singleton(void)
{
}
template <typename T>
Singleton<T>::Singleton(Singleton<T> const &other)
{
*this = other;
}
//Destruction
template <typename T>
Singleton<T>::~Singleton(void)
{
}
//Surcharges
template <typename T>
Singleton<T> &Singleton<T>::operator=(Singleton<T> const &other)
{
if (&other != this)
{
m_pInstance = other.m_pInstance;
m_Instance = other.m_Instance;
}
return (*this);
}
//Others
template <typename T>
T *Singleton<T>::GetSingletonPtr(void)
{
if (m_pInstance == NULL)
m_pInstance = new T();
return (m_pInstance);
}
template <typename T>
T &Singleton<T>::GetSingleton(void)
{
return (m_Instance);
}
template <typename T>
void Singleton<T>::DestroySingleton(void)
{
if (m_pInstance != NULL)
{
delete (m_pInstance);
m_pInstance = NULL;
}
}
}
然后,我在单例类“TestSingleton”的构造函数中使用日志“constructor:toto”编写了以下代码。
#include <iostream>
#include <Singleton.hpp>
class TestSingleton : public core::Singleton<TestSingleton>
{
friend class core::Singleton<TestSingleton>;
private:
TestSingleton(void)
{
std::cout << "constructor:toto" << std::endl;
}
};
class HandleSingleton
{
public:
void Handle()
{
TestSingleton &test = TestSingleton::GetSingleton();
}
};
int main(void)
{
getchar();
return (0);
}
输出如下:
$> constructor:toto
我不明白为什么即使未调用初始化此引用的方法(此处为“Handle”方法),也会初始化带有引用的变量?
预先感谢您的帮助!