Pastebin launched a little side project called VERYVIRAL.com, check it out ;-) Want more features on Pastebin? Sign Up, it's FREE!
Guest

Untitled

By: a guest on May 10th, 2012  |  syntax: C++  |  size: 1.21 KB  |  views: 91  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. #pragma once
  2.  
  3. template <class T> class ptr
  4. {
  5.         T* pointer;
  6.         unsigned int* counter;
  7. public:
  8.         ptr();
  9.         ptr(T* pointer);
  10.         ptr(const ptr<T>& copy);
  11.  
  12.         ~ptr();
  13.  
  14.         ptr<T>& operator=(const ptr<T>& copy);
  15.         operator T*();
  16.         T* operator->();
  17. };
  18.  
  19. template <class T> ptr<T>::ptr()
  20. {
  21.         pointer = nullptr;
  22.         counter = nullptr;
  23. }
  24.  
  25. template <class T> ptr<T>::ptr(T* pointer)
  26. {
  27.         this->pointer = pointer;
  28.         counter = new unsigned int();
  29.         *counter = 1;
  30. }
  31.  
  32. template <class T> ptr<T>::ptr(const ptr<T>& copy)
  33. {
  34.         pointer = copy.pointer;
  35.         counter = copy.counter;
  36.         if (counter != nullptr)
  37.         {
  38.                 (*counter)++;
  39.         }
  40. }
  41.  
  42. template <class T> ptr<T>::~ptr()
  43. {
  44.         if (counter != nullptr)
  45.         {
  46.                 (*counter)--;
  47.                 if (*counter == 0)
  48.                 {
  49.                         delete pointer;
  50.                         delete counter;
  51.                 }
  52.         }
  53. }
  54.  
  55. template <class T> ptr<T>& ptr<T>::operator=(const ptr<T>& copy)
  56. {
  57.         if (counter != nullptr)
  58.         {
  59.                 (*counter)--;
  60.                 if (*counter == 0)
  61.                 {
  62.                         delete pointer;
  63.                         delete counter;
  64.                 }
  65.         }
  66.  
  67.         pointer = copy.pointer;
  68.         counter = copy.counter;
  69.         if (counter != nullptr)
  70.         {
  71.                 (*counter)++;
  72.         }
  73.  
  74.         return *this;
  75. }
  76.  
  77. template <class T> ptr<T>::operator T*()
  78. {
  79.         return pointer;
  80. }
  81.  
  82. template <class T> T* ptr<T>::operator->()
  83. {
  84.         return pointer;
  85. }