对象实例可以使"this"无效吗?安全地指向自己的指针? [英] Can an object instance null out the "this" pointer to itself safely?

查看:63
本文介绍了对象实例可以使"this"无效吗?安全地指向自己的指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Class A
{
  public:
    NullIt()
    {
      this = NULL;
    }

    Foo()
    {
      NullIt();
    }
}

A * a = new A;
a->Foo();

assert(a);  //should assert here

有没有一种方法可以实现这种效果,将内存泄漏放在一边?

Is there a way to achieve this effect, memory leaks aside?

推荐答案

否.该对象对其外部引用(在本例中为"a")一无所知,因此无法更改它们.

No. The object knows nothing about the external references to it (in this case, "a"), so it can't change them.

如果您希望呼叫者忘记对象,则可以执行以下操作:

If you want the caller to forget your object, then you can do this:

class MyClass
{
    void Release(MyClass **ppObject)
    {
        assert(*pObject == this);   // Ensure the pointer passed in points at us
        *ppObject = NULL;           // Clear the caller's pointer
    }
}


MyClass *pA = new A;
pA->Release(&pA);
assert(pA);               // This assert will fire, as pA is now NULL

调用Release时,您将持有的指针传递给该对象,并且该对象将其变为NULL,以便在调用之后,指针为NULL.

When you call Release, you pass in the pointer you hold to the object, and it NULLs it out so that after the call, your pointer is NULL.

(Release()也可以删除它;"以便同时破坏自身)

(Release() can also "delete this;" so that it destroys itself at the same time)

这篇关于对象实例可以使"this"无效吗?安全地指向自己的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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