Re: Reference Counting
Joe Seigh wrote:
Thomas J. Gritzan wrote:
By assigning one smart pointer to another, you release the pointer on
the left hand side and copy the pointer from the right hand side to the
other.
So you have to decrement the lhs counter and increment the rhs counter.
But you must not delete the lhs pointer when the counter is not zero.
SmrtPtr<T>& operator=(const SmrtPtr<T>& rhs)
{
if(this!=&rhs)
{
this->DataBase.sub();
delete ptr;
The standard way of doing this is to do a copy ctor on the source,
swap with the destination, and let the dtor for the local copy,
which is now the destination, run when it goes out of scope
SmrtPtr<T>& operator=(const SmrtPtr<T>& rhs) {
SmrtPtr<T> temp(rhs);
swap(temp);
return *this;
}
You're safe in the case of source and destination being the same
since the refcount will be incremented before it gets decremented.
--
Joe Seigh
When you get lemons, you make lemonade.
When you get hardware, you make software.
OK, here's the new SmrtPtr class:
// COPYRIGHT CMDR DOUGLAS I. PEREIRA 07/10/06
// ALL UNAUTHORIZED THIRD PARTY USE IS PROHIBITED
// I HAVE WORKED VERY HARD AND HAVE SPENT HOURS OF
// TIME DEVELOPING THIS. DO NOT COPY IT OR I WILL SUE YOU
// ************************************************************
#pragma once
#include <iostream>
#include "SmrtPtrDB.hpp"
using namespace std;
class NullPtr{};
template<class T>
class SmrtPtr
{
public:
explicit SmrtPtr<T>(T* obj=0):ptr(obj), DataBase(new SmrtPtrDB){}
SmrtPtr<T>(const SmrtPtr<T>& rhs):ptr(rhs.ptr), DataBase(new
SmrtPtrDB(rhs.DataBase->status())){DataBase->add();}
~SmrtPtr<T>()
{
DataBase->sub();
if(DataBase->status()==0)
{delete ptr;cout << "Deleted." << endl;}
else cout << "Out of scope. " << endl;
}
void operator=(T val){if(ptr==0)throw NullPtr();else *ptr=val;}
void operator=(T* val){ptr=val;}
SmrtPtr<T>& operator=(const SmrtPtr<T>& rhs)
{
if(this!=&rhs)
{
SmrtPtr<T> temp(rhs);
swap(temp);
}
else return *this;
}
bool operator==(const SmrtPtr<T>& rhs)const{if(ptr==rhs.ptr)return
true;else return false;}
bool operator!=(const SmrtPtr<T>& rhs)const{if(ptr!=rhs.ptr)return
true;else return false;}
bool operator<=(const SmrtPtr<T>& rhs)const{if(ptr<=rhs.ptr)return
true;else return false;}
bool operator>=(const SmrtPtr<T>& rhs)const{if(ptr>=rhs.ptr)return
true;else return false;}
int status(){return DataBase->status();}
T& operator*()const{if(ptr==0)throw NullPtr();else return *ptr;}
T* operator->()const{if(ptr==0)throw NullPtr();else return ptr;}
operator T*()const{if(ptr==0)throw NullPtr();else return ptr;}
private:
void swap(SmrtPtr<T>& rhs){this=&rhs;}
mutable SmrtPtrDB* DataBase;
T* ptr;
};
Did I impl swap() correctly? Should DataBase be mutable?