muduo-ThreadLocal实现细节——阻止销毁未定义对象
muduo利用pthread_key_t实现ThreadLocal模板类.
具体代码如下所示:
1 template<typename T> 2 class ThreadLocal : noncopyable 3 { 4 public: 5 ThreadLocal() 6 { 7 MCHECK(pthread_key_create(&pkey_, &ThreadLocal::destructor)); 8 } 9 10 ~ThreadLocal() 11 { 12 MCHECK(pthread_key_delete(pkey_)); 13 } 14 15 T &value() 16 { 17 T *perThreadValue = static_cast<T *>(pthread_getspecific(pkey_)); 18 if (!perThreadValue) 19 { 20 T *newObj = new T(); 21 MCHECK(pthread_setspecific(pkey_, newObj)); 22 perThreadValue = newObj; 23 } 24 return *perThreadValue; 25 } 26 27 private: 28 29 static void destructor(void *x) 30 { 31 T *obj = static_cast<T *>(x); 32 typedef char T_must_be_complete_type[sizeof(T) == 0 ? -1 : 1]; 33 T_must_be_complete_type dummy; 34 (void) dummy; 35 delete obj; 36 } 37 38 private: 39 pthread_key_t pkey_; 40 };
代码除destructor均较为容易理解,故对此进行解释:
1 static void destructor(void *x) 2 { 3 T *obj = static_cast<T *>(x); 4 //对于只声明,未进行具体定义类型,例如A,sizeof(A)结果为0 5 //利用此特性,若T是未定义类型,则T_must_be_complete_type在编译期间会报错 6 typedef char T_must_be_complete_type[sizeof(T) == 0 ? -1 : 1]; 7 //消除unused-local-typedefs编译错误提示 8 T_must_be_complete_type dummy; 9 //消除Wno-unused-parameter编译错误提示 10 (void) dummy; 11 delete obj; 12 }
PS:
如果您觉得我的文章对您有帮助,可以扫码领取下红包,谢谢!