int main(int argc, char* argv[])
{
A * pa = new A;
pa->f(); // Question 1)
A a; // Question 2)
a.f(); // Question 3) program crashed
return 0;
}
Questions
1) when memory is allocated in heap by calling new, why "delete this" called in f() won't crash?
2) Class A doesn't have constructor so compiler generates a default constructor. Where is the memory for the new object is allocated since no new is called? still in heap?
3) Why calling a.f() makes it crashed?
4) Under what circumstances we want to call "delete this" (the example I gave of course is not why "delete this" is used, but there gotta be some situations justifies the calling of "delete this"?
1. Precisely because the object was allocated in the heap. Never forget that this is just a pointer to the object, and that non-static member functions are just functions that take an implicit argument (this).
2. On the stack.
3. Because the object in this case wasn't allocated on the heap. Using delete on a pointer that doesn't point to heap memory is illegal.
4. I can't think of any example where deleting this would be unavoidable. Generally speaking, if you do it, you're probably doing something wrong.
As far as Q4) goes, I saw somewhere saying "delete this" is useful for multi-threaded programming. But I am not sure. It will be helpful if I can find a good example. I will post here if I find one...
I also saw an example on Windows COM (Common Object Model) programming where no explicit deletion of a COM object should be called. Instead each COM object should call Release() which will call "delete this". But I don't know much about COM.
I read that "delete this" was bad before, for instance, when it's static then it can't find the object to delete.
So I changed f() to static, then it wouldn't even compile complaining that 'this' is unavailable for static member functions. I guess it's because the static method doesn't belong to any object so that's why it can't find the right object to delete, right? That's my Q5.
Now, I changed f() back to non-static, but I changed "A * pa = new A;" to "static A * pa = new A;".
When I ran it, it crashed?
Q6. Why did it crash? A static object can't be deleted, or a static object doesn't behave like a normal object? Where is the memory getting corrupted?
I read that "delete this" was bad before, for instance, when it's static then it can't find the object to delete.
If the function doing delete this is a static member function, then there is no this pointer. The program will simply not compile. So, my answer to your fifth question is yes.
6.
1 2
static A *pa=new A;
pa->f();
shouldn't fail, AFAICT. The static keyword merely changes where the pointer variable 'pa' is placed not the object itself. The object is still on the heap. The change should be irrelevant to A::f(), since only a copy of the pointer is passed.