转自http://www.cppblog.com/zmllegtui/archive/2008/10/27/65252.html
将构造函数设计成 protected 的目的是防止在 class 外面 new ,有人可能会设计成 private ,假如考虑到有可能会继续这个类的话,还是将构造函数设计成 protected 比较好,还需要加一个 virtual 析构函数。为了防止别人复制 Singleton 对象:
Singleton* pSingleton = Singleton::Instance();
Singleton s1 = *pSingleton;
Singleton s2 = *pSingleton;
需要将拷贝构造 (copy constrUCtor) 函数变成 private 。
但是这里存在的问题是,什么时候删除 Singleton 对象?按照 C++ 的一个基本原则,对象在哪里创建就在哪里销毁,这里还应该放一个 destroy 方法来删除 Singleton 对象。假如忘了删除就比较麻烦。 Instance 函数还存在多线程同时访问的加锁问题。假如把 Instance 函数开始和结尾放上加锁和解锁,整个函数性能会下降很多。这不是一个好的设计。
有一个小小的改动,可以避免忘了删除 Singleton 对象带来内存泄露的问题。那就是用 std:auto_ptr 来包含 Singleton 对象 , 定义一个 class static member auto_ptr 对象,在析构的静态 auto_ptr 变量的时候时候自动删除 Singleton 对象。为了不让用户 delete Singleton 对象,需要将析构函数由 public 变成 protected 。
写一个 C++ 中的 Singleton 需要这么费劲,大大出乎我们的意料。有很多人从未用过 auto_ptr ,而且 std:auto_ptr 本身就并不完美,它是基于对象所有权机制的,相比之下, Apache Log4cxx 中有一个 auto_ptr, 是基于对象计数的,更为好用。只是为了用一个好的 auto_ptr 而不得不用 log4cxx , 对于很多项目来说,也不太好。当然了, ANSI C++ 的 STL 中 std:auto_ptr 对于写上面的例子已经足够用了。 另外一个思路是,把 GetInstance 函数设计成 static member 可能更好,因为一般来说, Singleton 对象都不大, static member 虽然必须一直占用内存,问题不大。这里的析构函数必须设成 public 了。
从代码量来说,似乎使用 static member ref 更为简单。我更偏向于用这种方法。
但是,并不是所有情况下面都适合用 static member singleton 。比如说, GetInstance 需要动态决定返回不同的 instance 的时候,就不能用。举例来说, FileSystem::GetInstance, 在 windows 下面运行可能需要返回 new WinFileSystem, Linux/Unix 下面运行可能需要返回 new LinuxFileSystem ,这个时候还是需要用上面的 auto_ptr 包含 singleton 指针的方法。