Click here to Skip to main content
15,885,914 members
Articles / Programming Languages / C++

The fastest smart pointer in the west

Rate me:
Please Sign up or sign in to vote.
4.56/5 (18 votes)
7 Oct 200313 min read 111.7K   1.6K   41  
Need a super quick implementation of a reference counting smart pointer? AUTO_REF delivers just that, with a 'thin' source code of just 3,886 bytes (< 4KB)
#ifndef _AUTOREFH_LOADED_
#define _AUTOREFH_LOADED_


#include <windows.h>
#include <algorithm>
#include "quick_mem_manager.h"


//Prototypes
extern QUICK_MEM_MANAGER g_the_auto_ref_pool;
   
//AUTO_REF Class defintion
template <typename T>
class AUTO_REF {
private:
   long *m_ref_p;
   T *m_inst_p;

public:
   AUTO_REF(T *inst_p = 0) : m_inst_p(inst_p) {  //>x
      m_ref_p = static_cast<long*>(g_the_auto_ref_pool.malloc());
      *m_ref_p = 1;
   }

   AUTO_REF(const AUTO_REF<T> &other) 
      : m_ref_p(other.m_ref_p), m_inst_p(other.m_inst_p) {  //NOTHROW

      InterlockedIncrement(m_ref_p);
   }

   ~AUTO_REF() {  //NOTHROW
      if (!InterlockedDecrement(m_ref_p)) {
         delete m_inst_p;
         g_the_auto_ref_pool.free(m_ref_p);
      }
   }

   AUTO_REF &operator=(const AUTO_REF<T> &rhs) {  //NOTHROW

      AUTO_REF<T> temp(rhs);
      swap(temp);

      return *this;
   }

   T &operator*() const {     //NOTHROW
      return *m_inst_p;
   }

   T *operator->() const {    //NOTHROW
      return m_inst_p;
   }

   operator bool() const {    //NOTHROW
      return m_inst_p != 0;
   }

   T *get() const {           //NOTHROW
      return m_inst_p;
   }

   void swap(AUTO_REF<T> &other) {   //NOTHROW
      std::swap(m_ref_p, other.m_ref_p);
      std::swap(m_inst_p, other.m_inst_p);
   }

};//AUTO_REF

#endif //_AUTOREFH_LOADED_



By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Israel Israel
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions