class CObj{ DeleteMe() { delete this; } ~CObj() { /* will everything here be called? */ }};int main(){ CObj* ptr = new CObj; ptr->DeleteMe(); return 0;}
[Edited by - aeroz on June 22, 2008 5:09:10 AM]
class CObj{ DeleteMe() { delete this; } ~CObj() { /* will everything here be called? */ }};int main(){ CObj* ptr = new CObj; ptr->DeleteMe(); return 0;}
Quote:Original post by aeroz
So, is it safe on EVERY system to do this?
*** Source Snippet Removed ***
Quote:Original post by fpsgamer
It would be no more valid than doing this:
*** Source Snippet Removed ***
Once you delete the object, everything having to do with this is kaput, including the this pointer.
assert(myIntPtr != 0);
assert(this->myIntPtr != 0);
delete this;assert(this != 0);
int* p = new int [32]delete [] p;assert(p != 0);
Quote:int* p = new int [32]I don't think this is OK since you always have to set a pointer to NULL when you delete it, isn't it? At least I thought so. p would still be the address of the data that doesn't exist anymore.
delete [] p;
assert(p != 0);
which is OK afaik (I could be wrong though)
Quote:Original post by aeroz
@Gage64:
In the link you posted there nothing against my code?? In [16.15] it just says you mustn't play around with the this pointer when you have deleted it.
Quote:Original post by aeroz
So, is it safe on EVERY system to do this?
*** Source Snippet Removed ***
Quote:Original post by janta
Yes, you are dereferencing "this" in the following operationassert(myIntPtr != 0);
because it is equivalent toassert(this->myIntPtr != 0);
Quote:Original post by janta
you always have to set a pointer to NULL when you delete it, isn't it?
Quote:Original post by janta
which is indeed very bad, but I don't see howdelete this;assert(this != 0);
is any worse thanint* p = new int [32]delete [] p;assert(p != 0);
which is OK afaik (I could be wrong though)
{int* p = new int[32];delete [] p;assert(p != k); // this is o.k.}
delete this;assert(this != k); // this is bad
Quote:Original post by fpsgamer
However this is not okay:delete this;assert(this != k); // this is bad
You don't own the this pointer. The this pointer is only guaranteed to exist for as long as the object exists. Once the object is deleted, the this pointer and everything else associated with the object is invalid to use.
struct T { T() { int i = this; } }; // cannot convert from 'T *const ' to 'int'
Quote:In the body of a nonstatic (9.3) member function, the keyword this is a non-lvalue expression whose value is the address of the object for which the function is called.