I know it's going to hurt, but it's inevitable in learning good programming practices, isn't it?
Here's an intrusive reference counting implementation I've created after reading a chapter on handle classes in Stroustrup; it surely contains some ankward constructs that I've inevitably inserted into it as person who largely dealt with scripting for the last two years. I'd be grateful for suggestions and criticism on how to make it better.
Reference counted class:
class cRefCounted {
public:
cRefCounted() {
ref_count = 0;
}
void RefAdd() {
ref_count++;
}
void RefRemove() {
if(--ref_count<=0)
delete this;
}
std::string type() {
return typeid(this).name();
}
protected:
int ref_count;
};
Handle class:
template<class T> class tHandle {
public:
explicit tHandle(cRefCounted* obj) {
init(obj);
}
tHandle(const tHandle& handle) {
init(handle.obj);
}
virtual ~tHandle() {
obj->RefRemove();
}
T& operator*() const {
return *obj;
}
T* operator->() const {
return obj;
}
T* operator=(const tHandle& handle) {
if(handle.obj!=obj) init(handle.obj);
return obj;
}
protected:
T* obj;
void init(cRefCounted* obj) {
try {
this->obj = static_cast<T*>(obj);
obj->RefAdd();
}
catch(const std::bad_cast &e) {
fprintf(stderr, "Not an instance of cRefCounted\n");
this->obj = NULL;
}
}
};
Thanks in advance.












