#include <iostream>
using namespace std;
template <class T>
class shared_ptrx
{
private:
long *refcount;
T *link;
void decrement() {
if ((--(*refcount)) == 0) {
delete refcount;
if (link != NULL) {
delete link;
}
}
refcount = NULL;
link = NULL;
}
void init(T *t, long c) {
refcount = new long(c);
link = t;
}
void copy(shared_ptrx& p) {
refcount = p.refcount;
link = p.link;
(*refcount)++;
}
public:
shared_ptrx() { init(NULL, 0); }
explicit shared_ptrx(T *t) { init(t, 1); }
explicit shared_ptrx(shared_ptrx& p) { copy(p); }
~shared_ptrx() { decrement(); }
T& operator * () const { return *link; }
T* operator -> () const { return link; }
explicit operator bool () const {
if (refcount == NULL) return false;
return (*refcount > 0);
}
shared_ptrx& operator = (shared_ptrx& p) {
decrement();
copy(p);
return *this;
}
void reset(T *t) {
decrement();
init(t, 1);
}
void swap(shared_ptrx& p) {
int *rc = p.refcount;
T *temp = p.link;
p.refcount = refcount;
p.link = link;
refcount = rc;
link = temp;
}
};
template <class T>
class BaseList
{
private:
BaseList *link;
shared_ptrx<T> data;
public:
BaseList() : link(NULL) { }
BaseList(T *t) : link(NULL) { data.reset(t); }
void attach(const BaseList& p) {
link = &p;
}
};
class Value
{
int c;
public:
Value(int v) { c = v; }
~Value() { cout << "del!" << c << endl; }
void p() { cout << c << endl; }
operator int () { return c; }
};
int main() {
shared_ptrx<Value> f(new Value(5));
{
shared_ptrx<Value> p(f);
cout << *p << endl;
}
f->p();
{
shared_ptrx<Value> m(new Value(8));
shared_ptrx<Value> k(m);
k = f;
k->p();
m->p();
}
cout << "finish" << endl;
return 0;
}