"Alexander Stippler" <st**@mathematik.uni-ulm.de> wrote in message
news:3f******@news.uni-ulm.de...
| I have some question about the usage of delete. I have some reference
| counted classes, all derived from SharedObject. It's destructor looks like
| this:
|
| ~SharedObject()
| {
| if (--references_ == 0) {
| delete this;
| }
| }
This won't work. Once the destructor is executed, it is too late to
try to cancel the destruction process.
You need to use a different approach:
class SharedObject
{
public:
SharedObject() : refCnt(1) {}
void addRef() { ++refCnt; }
void release() { if(!--refCnt) delete this; }
protected:
virtual ~SharedObject()=0; // abstract class
private:
int refCnt;
};
SharedObject::~SharedObject() {}
Such a base class is usually combined with a smart pointer.
+ templates are to be considered for type safety.
Note that reference-counted classes is a well studied subject in C++.
Make sure to read advice from Scott Meyers and others on the subject.
Also, existing implementations such as boost::shared_ptr definitely
are to be considered:
http://www.boost.org/libs/smart_ptr/shared_ptr.htm
| Now I'd like to know if
| a) it's OK to use delete this (especially in the destructor)
Yes in rare and specific cases -- but never in the destructor.
| b) my guess, about what happens, is correct.
| In my understanding the destructor is entered and delete this is executed
| (if "if" is entered of course). Delete, as far as I know, calls the
| destructor of the object again, now the if-condition is false and the
| storage is freed due to the first call of delete.
This leads to undefined behavior. Not only is it illegal to call the
destructor twice. But also, the call to 'delete' will attempt to free
memory (=> the same memory block will be freed twice, or the call
will attempt to free a stack-based address... not good at all).
I hope this helps,