this pointer - deletion

S

srini4vasan

Can we delete 'this' pointer in C++.
If so how can we delete this pointer?
If not why?
 
G

Gianni Mariani

Can we delete 'this' pointer in C++.
If so how can we delete this pointer?
If not why?

Yes, you can delete the this pointer.

After calling "delete", you must not reference any non static member
variables or non static functions. Anything that causes you to
dereference the "this" pointer is bad news.
 
S

Stuart Redmann

Can we delete 'this' pointer in C++.
If so how can we delete this pointer?
If not why?

Of course you can delete the this pointer inside the method of a class (as
delete operator/operator delete (please don't flame me for not knowing which of
the terms is the correct one, I always forget which one means which)) does not
try to set the passed pointer to Null, you can pass any const pointer into
delete. Note that this is a technique that is used by the MS MFC library,
although calling "delete this" is frown upon by some programmers:

Excerpt from MFC implementation, I hope not to violate against some copyright
clauses:

// self destruction
void CView::postNcDestroy()
{
// default for views is to allocate them on the heap
// the default post-cleanup is to 'delete this'.
// never explicitly call 'delete' on a view
delete this;
}

This is quite handy for fire-and-forget implementation of Views (special windows
from the Document/view framework).

Regards,
Stuart
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,019
Latest member
RoxannaSta

Latest Threads

Top