Add reference count capability to your class with a template

发表于:2007-07-01来源:作者:点击数: 标签:
Because my system cant 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

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://www.ltesting.net