By the way... a somewhat smarter approach would be:
template<class T> class SmartPointer {
struct SPData {
SPData(T *obj){ m_ptr = obj; m_count = 1; }
~SPData(){ delete m_ptr; }
T* m_ptr;
uint m_count;
};
public:
SmartPointer(T *obj=0){
m_data = new SPData(obj);
}
~SmartPointer(){
deref();
}
SmartPointer(SmartPointer &other){
m_data = other.m_data;
ref();
}
SmartPointer &operator=(SmartPointer &other){
if(other.m_data==m_data)
return *this;
deref();
m_data = other.m_data;
ref();
}
SmartPointer &operator=(T *obj){
if(!m_data){
m_data = new SPData(obj);
return *this;
}
if(obj==m_data->m_ptr) return *this;
m_data->deref();
m_data = new SPData(obj);
return *this;
}
bool operator==(SmartPointer &other) const{ return m_data==other.m_data; }
T operator*(){ return m_data ? m_data->m_ptr : T(); }
const T* operator T*() const { return m_data ? m_data->m_ptr : 0; }
private:
SPData *m_data;
void deref(){
if(!m_data) return;
if((--(m_data->m_count))==0){
delete m_data;
}
}
void ref(){
m_data->m_count++;
}
int m_count;
};
template<class T> class SmartPointer {
struct SPData {
SPData(T *obj){ m_ptr = obj; m_count = 1; }
~SPData(){ delete m_ptr; }
T* m_ptr;
uint m_count;
};
public:
SmartPointer(T *obj=0){
m_data = new SPData(obj);
}
~SmartPointer(){
deref();
}
SmartPointer(SmartPointer &other){
m_data = other.m_data;
ref();
}
SmartPointer &operator=(SmartPointer &other){
if(other.m_data==m_data)
return *this;
deref();
m_data = other.m_data;
ref();
}
SmartPointer &operator=(T *obj){
if(!m_data){
m_data = new SPData(obj);
return *this;
}
if(obj==m_data->m_ptr) return *this;
m_data->deref();
m_data = new SPData(obj);
return *this;
}
bool operator==(SmartPointer &other) const{ return m_data==other.m_data; }
T operator*(){ return m_data ? m_data->m_ptr : T(); }
const T* operator T*() const { return m_data ? m_data->m_ptr : 0; }
private:
SPData *m_data;
void deref(){
if(!m_data) return;
if((--(m_data->m_count))==0){
delete m_data;
}
}
void ref(){
m_data->m_count++;
}
int m_count;
};
To copy to clipboard, switch view to plain text mode
Note that this code is not reentrant and was not tested thus it probably contains some errors. Furthermore the mechanism will still break down if you delete the pointer yourself somewhere. But the advantage is that all objects track the number of references to the object and the object will get deleted when nothing points to it anymore. If you want, you can also add a possibility to force the deletion by adding the following method:
void SmartPointer::forceDelete(){
if(!m_data) return;
delete m_data->m_ptr;
m_data->m_ptr = 0;
}
void SmartPointer::forceDelete(){
if(!m_data) return;
delete m_data->m_ptr;
m_data->m_ptr = 0;
}
To copy to clipboard, switch view to plain text mode
Adding isValid() or isNull() methods would also be a good move then.
Bookmarks