#ifndef _LEPTO_SHARED_PTR_H_
#define _LEPTO_SHARED_PTR_H_
//----------------------------------------------------------------------------
///
/// \file   shared_ptr.h
///
/// \brief  Shared pointer
///
///         See implementation files for further information
///
/// \date   20170822
/// \author Maximilian Seesslen <mes@seesslen.net>
///
//----------------------------------------------------------------------------


//---Documentation-------------------------------------------------------------


//---Includes -----------------------------------------------------------------


//---General--------------------------


#include <stdio.h>      // printf

//---Defines ------------------------------------------------------------------


//---Definitions---------------------------------------------------------------


template <typename T>
class CSharedPointer: public CDebug
{
   protected:
      T *m_ptr;
      int *m_counter;

   private:

   public:
      CSharedPointer()
         :m_ptr(0)
         ,m_counter(0)
      {
      };

      ~CSharedPointer()
      {
         //printf("DS SP\n");

         if(m_counter)
         {
            (*m_counter)--;
            if(!((*m_counter)))
            {
               delete m_ptr;
               delete m_counter;
            }
         }
         m_counter=0;
         m_ptr=0;
      };

      CSharedPointer(const CSharedPointer &copy)
      {
         m_ptr=copy.m_ptr;
         m_counter=copy.m_counter;
         (*m_counter)++;
         //printf("CC\n");
         //puts("C\n");
      }

      CSharedPointer &operator=(const CSharedPointer &copy)
      {
         // I am pointing to something
         if(m_counter)
         {
            (*m_counter)--;
            if(!((*m_counter)))
            {
               delete m_ptr;
               delete m_counter;
            }
         }

         m_ptr=copy.m_ptr;
         m_counter=copy.m_counter;
         (*m_counter)++;
         printf("CC SP %d\n", (*m_counter));
         return(*this);
      }

      CSharedPointer(T *buf)
         :m_ptr(buf)
      {
         m_counter=new int;
         *m_counter=1;
         printf("CreateConstructorC SP %d\n", (*m_counter));
      }

      T &operator *() const
      {
         return(*m_ptr);
      }

      operator bool() const
      {
         return( m_ptr != 0 );
      }

      T *operator->() const
      {
         return(m_ptr);
      }
};


//---fin----------------------------------------------------------------------
#endif // ? ! _LEPTO_SHARED_PTR_H_
