Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing a local variable after "delete this"

Tags:

c++

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();
    }
};
like image 591
FireAphis Avatar asked Aug 06 '10 09:08

FireAphis


People also ask

Do local variables get deleted?

The local variables that are allocated on stack, i.e. without using memory allocation functions or operators like malloc and new , are deleted automatically. All other variables have to be deleted by using delete as they are stored on heap.

What does delete this do?

"delete this" in C++? Delete is an operator that is used to Deallocate storage space of Variable. This pointer is a kind of pointer that can be accessed but only inside nonstatic member function and it points to the address of the object which has called the member function.

Can we access local variable?

Yes, we can access the local final variables using the method local inner class because the final variables are stored on the heap and live as long as the method local inner class object may live.

How do you delete a local variable in C++?

there is no way to "delete" it. It is either a global variable, with statically allocated storage, or it is a local variable with storage on the stack. As you suggest in your question, you will almost always be better off using std::vector , std::list , and the like rather than using raw C-style arrays.


2 Answers

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.)

like image 170
Konrad Rudolph Avatar answered Nov 14 '22 23:11

Konrad Rudolph


Yes, you can, but why not to use atomic decrement instead of decrementing the counter under the mutex? And do you actually need to protect (by mutex) object destruction? Indeed, after counter becames 0 the only current thread can acess the object.

So, maybe it is possible to rewrite your code as

     int tmp_count;
     m.Acquire();
        tmp_count= --recount_;
     m.Release();
     if (tmp_count &lt= 0)  delete this;

(or use atomics to decrement and test the counter)

like image 43
user396672 Avatar answered Nov 14 '22 22:11

user396672