在"删除此"之后访问本地变量

Fir*_*his 7 c++

我有一个使用引用计数机制的类.delete this当引用计数降为零时,最终通过调用来销毁此类的对象.我的问题是:我之后可以使用本地堆栈变量delete this吗?这是一个更具体的例子:

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();
    }
};
Run Code Online (Sandbox Code Playgroud)

Kon*_*lph 7

是的,您可以这样做,只要成员变量本身实际上只是对外部对象的引用.

(请原谅以前的错误答案,我对mutex_变量感到困惑.)