Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

this = 0 ?

Status
Not open for further replies.

trollacious

Programmer
Sep 29, 2004
4,046
US
Is there any way in a destructor to automatically set the "this" pointer to zero, or NULL?

Lee
 
I don't think so, but I haven't tried.
Why would anyone want to?
 
this is a local const pointer. It can't be equal to 0. Moreover, a class destructor does not free object memory slot.
 
Setting a pointer to zero is one often suggested to help prevent attempts to access deallocated memory. I have seen many C/C++ programs written where the pointer is explicitly set to NULL or 0 by the programmer right after the object is deleted, and was just wondering if it was possible to automatically have the destructor handle this.

Setting a pointer to NULL or 0 is a technique for checking if an object has been deleted or not, and is generally considered good practice in creating bug-free programs.

Lee
 
OK, I think what you're looking for is a RAII object.
If you go to you should check out their smart pointers. You could also use the auto_ptr class from the STL, but Boost has a better one.
 
The problem is that even if you could set the this pointer to 0, it wouldn't affect any other existing pointers that point to the object being destructed, and would therefore be useless. It is the other existing pointers that must be set to null after the memory is deleted and the object is destroyed. Modifying "this" won't do that.
 
Yes, you usually assign 0 to the ptr you delete.

But you don't delete 'this' in the destructor (and you didn't new it in the constructor), and consequently you don't set it to 0 either.

>Setting a pointer to NULL or 0 is a technique for checking if an object has been deleted or not, and is generally considered good practice in creating bug-free programs.

Quite true. But 'this' isn't for you to delete.

Besides, after you leave the destructor there won't be a 'this' anyway, so...

/Per

www.perfnurt.se
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top