在“删除此”之后访问本地变量 [英] Accessing a local variable after "delete this"

查看:115
本文介绍了在“删除此”之后访问本地变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用引用计数机制的类。当引用计数下降到零时,通过调用 delete this 最终会破坏这个类的对象。我的问题是:我可以使用本地堆栈变量删除此?这里有一个更具体的例子:

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();
    }
};


推荐答案

href =https://isocpp.org/wiki/faq/freestore-mgmt#delete-this =nofollow>您可以这样做,只要会员变量本身只是一个对外部对象的引用。

Yes, you may do this, as long as the member variable itself is really only a reference to an external object.

(请原谅以前的错误答案,我对 mutex _ variable。)

(Please forgive the previous wrong answer, I was confused about the mutex_ variable.)

这篇关于在“删除此”之后访问本地变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆