在工作中遇到不少情况使用singleton模式,下面采用的是最简单的一种形式:
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 };
2 {
3 public :
4 static Foo & getSingleton()
5 {
6 static Foo foo;
7 return foo;
8 }
9
10 private :
11 Foo();
12 };
这种实现,在单线程情况下,简单而有效。
对于线程安全的singleton的实现,网上有不少讨论。这两天看到boost库中的一种实现,没有使用锁机制,而是充分利用了C++的语言特性较好的解决了多线程情况下使用singleton的问题。
boost的singleton的实现基于以下假设:良好的设计在进入main函数之前应该是单线程的。
我们可以使用全局变量的方式来设计singleton,并且保证在使用该singleton之前其已经被正确的初始化,如何做到?且看代码:
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 };
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 };
漂亮而巧妙的实现。
但是上面的实现还是有一点小的缺憾,那就是只能调用类的默认构造函数,不能调用带参数的构造函数。