I have a class that employs a reference counting mechanism. The objects of this class are eventually destroyed by calling delete this when the reference count drops to zero. My question is: can I use local on-stack variable after delete this? Here’s a more specific example:
class RefCountedClass
{
public:
RefCountedClass(Mutex& m) :
mutex_(m)
{}
.
.
.
private:
Mutex& mutex_;
void RemoveReference()
{
// As I understand, mutex_ will be destroyed after delete,
// but using m is all right because it is on-stack and
// references an external object. Am I right?
Mutex& m = mutex_;
m.Acquire();
--recount_;
if (refcount <= 0) delete this;
m.Release();
}
};
Yes, you may do this, as long as the member variable itself is really only a reference to an external object.
(Please forgive the previous wrong answer, I was confused about the
mutex_variable.)