- 论坛徽章:
- 0
|
一个singleton模板实现的练习
Sing.h
- #include <pthread.h>
- template <class T> class CTplSingleton
- {
- private:
- static T _instance;
- static pthread_mutex_t mutex;
- protected:
- CTplSingleton<T>& operator=(const CTplSingleton<T>&);
- CTplSingleton();
- ~CTplSingleton();
- public:
- static T& instance();
- };
复制代码
Sing.cpp
- #include "Sing.h"
- //static member data
- template<class T> pthread_mutex_t CTplSingleton<T>::mutex = PTHREAD_MUTEX_INITIALIZER;
- template<class T> T CTplSingleton<T>::_instance;
- //protected member function
- template <class T> CTplSingleton<T>::CTplSingleton()
- {}
- template <class T> CTplSingleton<T>::~CTplSingleton()
- {}
- template <class T> CTplSingleton<T>& CTplSingleton<T>::operator=(const CTplSingleton<T>&)
- {}
- //public member function
- template <class T> T& CTplSingleton<T>::instance()
- {
- if( 0 == _instance )
- {
- pthread_mutex_lock(&mutex);
- if( 0 == _instance )
- {
- _instance = * new T;
- }
- pthread_mutex_unlock(&mutex);
- }
- return _instance;
- }
复制代码
demo.cpp
- #include "Sing.h"
- int main()
- {
- int ref = CTplSingleton<int>::instance();
- }
复制代码
g++ demo.cpp Sing.cpp -Wall
demo.cpp: In function `int main()':
demo.cpp:65: warning: unused variable `int ref'
/tmp/ccV1tcJm.o(.text+0x11): In function `main':
: undefined reference to `CTplSingleton<int>::instance()'
collect2: ld returned 1 exit status
[root@VM template]# uname -a
Linux VM 2.4.20-8 #1 Thu Mar 13 17:54:28 EST 2003 i686 i686 i386 GNU/Linux
[root@VM template]# g++ --version
g++ (GCC) 3.2.2 20030222 (Red Hat Linux 3.2.2-5)
Copyright (C) 2002 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
静态成员函数应该怎么用的?
[ 本帖最后由 andyY 于 2006-10-25 13:40 编辑 ] |
|