Click here to Skip to main content
Click here to Skip to main content
Add your own
alternative version
Go to top

The fastest smart pointer in the west

, 7 Oct 2003
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

Share

About the Author

Itay Maman

Israel Israel
No Biography provided

| Advertise | Privacy | Mobile
Web01 | 2.8.140916.1 | Last Updated 8 Oct 2003
Article Copyright 2001 by Itay Maman
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid