T
Tom Smith
I'm writing my own smart pointer class (as an exercise, not for real life use);
I've got it to a point where I think it's usable: but I'm not quite sure. Any
comments on the class gratefully received.
Cheers - Tom
/** code starts here **/
/** **/
/** obviously ! **/
#include <map>
template <class T> class ptr
{
public:
inline ptr() : t(null_t) { };
inline ptr(ptr<T> const& other) : t (other.t)
{ Count[t]++; }
inline ptr(T* const t2) : t (t2)
{ Count[t]++; }
inline ~ptr()
{ Count[t]--; if (Count[t]==0 && t != null_t) delete t; }
ptr<T> operator= (T* const t2)
{ Count[t]--; if (Count[t]==0 && t != null_t) delete t; Count.erase(t); t
= t2; Count[t]++; }
ptr<T> operator= (ptr<T> const& other)
{ Count[t]--; if (Count[t]==0 && t != null_t) delete t; Count.erase(t); t
= other.t; Count[t]++; }
bool operator== (ptr<T> const& other)
{ return (t == other.t); }
bool operator== (T* const t2)
{ return (t == t2); }
T* operator-> () { return t; }
operator T* () { return t; }
T* operator() (){ return t; }
private:
T* t;
static std::map<T*, int> Count;
static T* const null_t;
};
template <class T> std::map<T*, int> ptr<T>::Count;
template <class T> T* const ptr<T>::null_t = 0;
I've got it to a point where I think it's usable: but I'm not quite sure. Any
comments on the class gratefully received.
Cheers - Tom
/** code starts here **/
/** **/
/** obviously ! **/
#include <map>
template <class T> class ptr
{
public:
inline ptr() : t(null_t) { };
inline ptr(ptr<T> const& other) : t (other.t)
{ Count[t]++; }
inline ptr(T* const t2) : t (t2)
{ Count[t]++; }
inline ~ptr()
{ Count[t]--; if (Count[t]==0 && t != null_t) delete t; }
ptr<T> operator= (T* const t2)
{ Count[t]--; if (Count[t]==0 && t != null_t) delete t; Count.erase(t); t
= t2; Count[t]++; }
ptr<T> operator= (ptr<T> const& other)
{ Count[t]--; if (Count[t]==0 && t != null_t) delete t; Count.erase(t); t
= other.t; Count[t]++; }
bool operator== (ptr<T> const& other)
{ return (t == other.t); }
bool operator== (T* const t2)
{ return (t == t2); }
T* operator-> () { return t; }
operator T* () { return t; }
T* operator() (){ return t; }
private:
T* t;
static std::map<T*, int> Count;
static T* const null_t;
};
template <class T> std::map<T*, int> ptr<T>::Count;
template <class T> T* const ptr<T>::null_t = 0;