1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
|
#ifndef SHARED_PTR_H
#define SHARED_PTR_H
#include <stdexcept>
/**
* EXAMPLE IMPLEMENTATION! DO NOT EVEN THINK TO USE!
*/
template <class T>
class shared_ptr
{
class holder
{
public:
holder()
: p(0),
counter(1)
{
}
holder(T* t)
: p(t),
counter(1)
{
}
~holder()
{
delete p;
}
T* p;
int counter;
private:
holder& operator=(const holder&);
holder(const holder&);
};
holder* h_;
public:
~shared_ptr()
{
if (--h_->counter == 0)
{
delete h_;
}
}
shared_ptr()
: h_(new holder())
{
}
shared_ptr(T* t)
: h_(new holder(t))
{
}
shared_ptr(const shared_ptr& rhl)
: h_(rhl.h_)
{
++h_->counter;
}
shared_ptr& operator=(const shared_ptr& rhl)
{
if (this == &rhl)
{
return *this;
}
if (--h_->counter == 0)
{
delete h_;
}
h_ = rhl.h_;
++h_->counter;
return *this;
}
shared_ptr& operator=(T* t)
{
if (--h_->counter == 0)
{
delete h_;
}
h_ = new holder(t);
return *this;
}
T* get() const
{
return h_->p;
}
T* operator ->() const
{
if (h_->p == 0)
{
throw std::runtime_error("null pointer dereferenced");
}
return h_->p;
}
void reset(T* t = 0)
{
if (--h_->counter == 0)
{
delete h_;
}
h_ = new holder(t);
}
int count() const
{
return h_->counter;
}
};
#endif
|