在工作中遇到不少情況使用singleton模式,下面采用的是最簡(jiǎn)單的一種形式:
1 class Foo
2 {
3 public:
4 static Foo& getSingleton()
5 {
6 static Foo foo;
7 return foo;
8 }
9
10 private:
11 Foo();
12 };
這種實(shí)現(xiàn),在單線程情況下,簡(jiǎn)單而有效。
對(duì)于線程安全的singleton的實(shí)現(xiàn),網(wǎng)上有不少討論。這兩天看到boost庫(kù)中的一種實(shí)現(xiàn),沒(méi)有使用鎖機(jī)制,而是充分利用了C++的語(yǔ)言特性較好的解決了多線程情況下使用singleton的問(wèn)題。
boost的singleton的實(shí)現(xiàn)基于以下假設(shè):良好的設(shè)計(jì)在進(jìn)入main函數(shù)之前應(yīng)該是單線程的。
我們可以使用全局變量的方式來(lái)設(shè)計(jì)singleton,并且保證在使用該singleton之前其已經(jīng)被正確的初始化,如何做到?且看代碼:
1 template <typename T>
2 struct Singleton
3 {
4 struct object_creator
5 {
6 object_creator(){ Singleton<T>::instance(); }
7 inline void do_nothing()const {}
8 };
9
10 static object_creator create_object;
11
12 public:
13 typedef T object_type;
14 static object_type& instance()
15 {
16 static object_type obj;
17 create_object.do_nothing();
18 return obj;
19 }
20
21 };
漂亮而巧妙的實(shí)現(xiàn)。
但是上面的實(shí)現(xiàn)還是有一點(diǎn)小的缺憾,那就是只能調(diào)用類的默認(rèn)構(gòu)造函數(shù),不能調(diào)用帶參數(shù)的構(gòu)造函數(shù)。
附:
非常抱歉,上面這個(gè)代碼是有點(diǎn)問(wèn)題的。感謝各位童鞋及時(shí)回復(fù)并指出問(wèn)題所在。現(xiàn)在補(bǔ)上缺失的初始化部分。
1 template <typename T>
2 typename Singleton<T>::object_creator
3 Singleton<T>::create_object;