Milind Arun Choudhary's Weblog

http://www.csl.mtu.edu/~machoudh/

Posts Tagged ‘reference count’

Implement simple reference counting in C++ using smart pointer

Posted by milindchoudhary on March 21, 2009

#include

using namespace std;

class fsptr;

class fs
{
public:
friend class fsptr;
static fsptr create();
static fsptr create(int);
void display(void);
fs::~fs();
private:
fs();
fs(int);
int _refcnt;
int _data;
};

fs::fs(): _refcnt(0),_data(0)
{
cout <<” fs::fs() ” << endl;
}

fs::fs(int i): _refcnt(0),_data(i)
{
cout <<” fs::fs(i) ” << endl;
}

fs::~fs()
{
cout <<” fs::~fs() ” << endl;
}

void fs::display(void)
{
cout <<” fs::display() ” << this << endl;
}

/*
fs::fs(const fs& cp): _refcnt(0)
{
cout <<” fs::fs(fs&) ” <();
fs& operator*();
private:
fs* _fsobj;
};

fsptr::fsptr(fs* fsobj )
:_fsobj ( fsobj)
{
cout <<“fsptr::fsptr(fs*)” <_refcnt);
}

fsptr::fsptr(const fsptr& cp)
: _fsobj ( cp._fsobj)
{
cout <<“fsptr::fsptr(fsptr&)” <_refcnt);
}

fsptr& fsptr::operator=(const fsptr& rhs)
{
cout <<“fsptr::operator=(fsptr& rh)” <_refcnt);

return (*this);

}

fs* fsptr::operator->()
{
cout <” << endl;
return _fsobj;
}

fs& fsptr::operator*()
{
cout <<“fsptr::operator*” << endl;
return (*_fsobj);
}

fsptr::~fsptr()
{
cout << “fsptr::~fsptr”<_refcnt) ==0){
cout << “recnt down to zero ..deleting obj” << endl;
delete _fsobj;
}
}

fsptr fs::create()
{
cout <<” fs::create() ” << endl;
return fsptr(new fs());
}

fsptr fs::create(int i)
{
cout <<” fs::create(i) ” <display();
(*fp1).display();
fsptr fp2 = fp1;
fp2->display();
(*fp2).display();

return 0;
}

Advertisements

Posted in Uncategorized | Tagged: , , | Leave a Comment »