#include <iostream>
using namespace std;
template<
class T>
class shared_ptr
{
typedef T& reference;
typedef T* pointer;
typedef unsigned long size_type;
private:
T *px;
size_type* pn;
public:
explicit shared_ptr() : px(
0), pn()
{
}
template<
typename Y>
shared_ptr(Y* py)
{
pn =
new size_type(
1);
px = py;
}
shared_ptr(
const shared_ptr& r)
throw() : px(r.px)
{
++*r.pn;
pn = r.pn;
}
template<
typename Y>
shared_ptr(
const shared_ptr<Y>& r)
{
px = r.px;
++*r.pn;
pn = r.pn;
}
~
shared_ptr() { dispose(); }
shared_ptr&
operator=(
const shared_ptr& r)
throw()
{
if (
this == &r)
return *
this;
dispose();
px = r.px;
++*r.pn;
pn = r.pn;
return *
this;
}
template<
typename Y>
shared_ptr&
operator=(
const shared_ptr<Y>& r)
{
dispose();
px = r.px;
++*r.pn;
pn = r.pn;
return *
this;
}
void reset(T* p =
0)
{
if (px == p)
return;
if (--*pn ==
0)
{
delete(px);
}
else
{
try { pn =
new size_type; }
catch (...) {
++*pn;
delete(p);
throw;
}
}
*pn =
1;
px = p;
}
reference
operator*()
const throw(){
return *px; }
pointer
operator->()
const throw(){
return px; }
pointer get()
const throw(){
return px; }
size_type use_count()
const throw()
{
return *pn;
}
bool unique()
const throw()
{
return *pn ==
1;
}
private:
void dispose()
throw()
{
if (--*pn ==
0)
{
delete px;
delete pn;
}
}
};
template<
typename A,
typename B>
inline bool operator==(
shared_ptr<A>
const & l,
shared_ptr<B>
const & r)
{
return l.get() == r.get();
}
template<
typename A,
typename B>
inline bool operator!=(
shared_ptr<A>
const & l,
shared_ptr<B>
const & r)
{
return l.get() != r.get();
}
int main()
{
shared_ptr<
int> sp(
new int(
2) );
shared_ptr<
int> sp2( sp );
cout << *sp << ends << *sp2 << endl;
cout << sp.use_count() << ends << sp2.use_count() << endl;
return 0;
}
输出: 2 2 2 2