1. #include"SingletonUseStaticClassMember.h"
2.
3. SingletonUseStaticClassMemberSingletonUseStaticClassMember::m_oInstance;
4.
5. SingletonUseStaticClassMember*SingletonUseStaticClassMember::GetInstance()
6. {
7. return&m_oInstance;
8. }
9.
10. SingletonUseStaticClassMember::SingletonUseStaticClassMember(void)
11. {
12. }
13.
14. SingletonUseStaticClassMember::~SingletonUseStaticClassMember(void)
15. {
16. m_i=10;
17. }
18.
19. intSingletonUseStaticClassMember::SomeFunction()
20. {
21. return10;
22. }
在单例类中定义一个本类的静态成员,这种方式实例类的析构函数会被调用,一切都是正确的,但是这种
方式很不好,不能够延迟创建实例类,实际上相当于系统定义了一个全局的类变量,生存期同应用程序一
样,从这个角度看甚至还不如第一种做法。
3、使用函数的静态变量实现单例模式
SingletonUseStaticFunctionVariable 类定义
[cpp]view plain copy
1. classSingletonUseStaticFunctionVariable
2. {
3. private:
4. SingletonUseStaticFunctionVariable(void);
5. public:
6. staticSingletonUseStaticFunctionVariable*GetInstance();
7. ~SingletonUseStaticFunctionVariable(void);
8.
9. intm_i;
10. public:
11. intSomeFunction();
12. };