Add reference count capability to your class with a template class

类别:VC语言 点击:0 评论:0 推荐:

Because my system can't install Chinese IME, so... In fact, everyone read this article should know my english is very pool.

// This template class is used to add "ref count" feature for any class
template <class T>
class CRefObject : public T
{
public:
 DWORD AddRef(void)
 {
  return ::InterlockedIncrement((LPLONG)&m_dwRef);
 }
 DWORD Release(void)
 {
  if (0 == m_dwRef ||
   0 == ::InterlockedDecrement((LPLONG)&m_dwRef))
  {
   delete this;
   return 0;
  }
  return m_dwRef;
 }
 // Create an instance buf ref == 0
 static CRefObject<T> * CreateInstance(void)
 {
  CRefObject<T> * p = NULL;
  p = new CRefObject<T>();
  return p;
 }
protected:
 // Note: All T MUST have a default constructor
 CRefObject(void) : m_dwRef(0)
 {
 }
 // I think it is unnecessary to define a "virtual" distrcutor
 ~CRefObject() {};
 DWORD m_dwRef;
};

 

本文地址:http://com.8s8s.com/it/it2594.htm