最近看了adrianx的大作《C++实现单件的初探》,真是讲得很好,不过里面有一处疏漏。
现对其Singleton类的设计分析如下:
首先,让我们来对Singleton类进行如下测试:
#include <iostream> using namespace std;
// 为了给Singleton类的Instance计数 template <typename T> class Counter { public: Counter() { ++count; } ~Counter() { --count; }
Counter(const Counter&) { ++count; } static size_t HowMany() { return count; }
private: static size_t count; };
class Singleton : private Counter<Singleton> { private: Singleton() { cout<<"object is ["<<this<<"] Do< Construction"<<endl; } public: using Counter<Singleton>::HowMany; // Added by jfwan
~Singleton() { cout<<"object is ["<<this<<"] Do Destruction>"<<endl; }
static Singleton & GetSingleton() { static Singleton s; return s; } void Dosomething() { cout<<"object is ["<<this<<"] Do Something"<<endl; } };
int main(int argc, char* argv[]) { Singleton& first = Singleton::GetSingleton();
Singleton second(first); // 1
Singleton third(first); // 2
cout << "There are " << Singleton::HowMany() << " instances of Singleton." << endl;
return 0; }
执行结果:
object is [0049F1C0] Do< Construction There are 3 instances of Singleton. object is [0012FEB3] Do Destruction> object is [0012FEBF] Do Destruction> object is [0049F1C0] Do Destruction>
可以看出Singleton产生了三个Instance,但Construction却只被调用了一次,不难看出另外两个Instance是被Copy Ctor构造出来的,到此,我们已经找到了这段程序中的这个小小的bug了,但如何来去掉这只‘臭虫‘呢?
当我们不定义Copy Ctor时,编译器在需要的时候会产生一个默认的Copy Ctor。分析上面的代码,对于Singleton Pattern,1,2两处的用法应该被禁止,对于1,2这种情况来说是很容易的(但它确实应该被禁止掉)。但一旦在程序中有意或无意的使用了by-value的方式进行函数调用
,就不易被我们所发现。这种情况我们应该尽量使它们在compile-time暴露出来。我们可以通过将Destructor置于private section的方法使1,2不能在此定义。因为Singleton的Destructor属于private section, Compiler将如是抱怨!于是...
但是对于某些类来说,Destructor并不是必需的,而且,有Destructor会降低performance(虽然那只是一点点,但既然我们能避免,又何乐而不为呢)。因此通过改变Destructor的Access level并不是十分明智!然而我们应该如何阻止诸如1,2之类的行为发生呢?Let me think...
嗯!我们得避免编译器合成Default copy constructor行为的产生,然而怎样才能达到这一目的呢?所幸的是,避免编译器的这种幕后操作并不难。
且看修改后的Singleton类如下所示:
class Singleton : private Counter<Singleton> { // 同上
private: // preventions Singleton(const Singleton&); Singleton& operator = (const Singleton&); };
我将Singleton的Copy ctor和Assignment operator声明为private, 并且不提供定义(这是为了避免被friend或member functions调用)。这样我们就可以很明显的使1,2出通不过Compiler!使得该Singleton类成为Singleton Pattern的比较完美的实现。
完整代码如下:
class Singleton { private: Singleton() { cout<<"object is ["<<this<<"] Do< Construction"<<endl; } public: ~Singleton() { cout<<"object is ["<<this<<"] Do Destruction>"<<endl; }
static Singleton & GetSingleton() { static Singleton s; return s; } void Dosomething() { cout<<"object is ["<<this<<"] Do Something"<<endl; }
private: // preventions Singleton(const Singleton&); Singleton& operator = (const Singleton&); };
至此,我们的Singleton类就设计完成了!其中难免还有遗漏之处,还望各位不吝指教!
[email protected] 
|