Tutorial :Can an object instance null out the “this” pointer to itself safely?



Question:

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?


Solution:1

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  

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() can also "delete this;" so that it destroys itself at the same time)


Solution:2

Exactly what effect are you trying to acheive?

Even if you could assign a new pointer (or NULL) to 'this' (which you can't), it wouldn't affect the pointer 'a'.


Solution:3

this is a constant pointer. You can change what it points to but you can't change the pointer itself.

As noted in comments, yes, you can cast the const away, but even if you change that, it's just a local variable. It won't affect the actual outside reference.


Solution:4

I can't see any reason you would ever want to do this. It would cause a memory leak, as a would be floating around presumably without any pointers to it. And I'm almost certain you can't assign to this anyway, largely because it doesn't make any sense. Why do you want to do it?


Solution:5

Think about why the following won't do what you want:

A *a = new A;  A *b = a;  a = NULL;  assert(b);  

and you'll see why setting this to NULL won't work.


Solution:6

The 'this' pointer is simply the address of the instance of the object your code is in. Setting this = null; isn't allowed because it doesn't make sense. It would appear your looking for

Class A  {    public:      ~A     {        // clean up A     }  }    A * a = new A;  delete a;    assert(a);  //should assert here  

This will free the instance from memory. However if you have any other references to a, those pointers will still be pointing where that instance was (not good!) and need to be set to null.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »