On Oct 15, 6:22*am, thomas <freshtho...@gmail.com> wrote:
> Hi,
>
> ------------
> class A {
> public:
> * * * ~A(){}
> * * * *void Release(){ delete this; }};
>
> -----------
> A *a = new A();
> a->Release(); * * * --> * *Method I
> A a2;
> a2.Release(); * * *--> * *Method II
> -----------
>
> a is created in Heap while a2 is in Stack.
> When I call "Release()", thus "delete this;" to these two different
> kinds of object, what will happen?
> If "delete this" just involves calling the destructor, I suppose they
> are equivalent.
Not at all. operator delete invokes the destrucctor and then frees
allocated memory. Just like operator new allocates memory, then calls
the constructor. That's a rather fundamental aspect of what they do.
> Any suggestions? Thanks.
Others already explained.
I'll add this: "delete this" is in general a bloody stupid idea with
rare situations where it's expedient. Your snippet is just a massive
bug.
C++ language, however, does allow you to design a type so that clients
have to use it on the heap, and that you have to call e.g. a Release
function (name is incidental). E.g.
class heap_only_please
{ // intentionally private:
heap_only_please() {...}
heap_only_please(const heap_only_please& ) {...};
~heap_only_please() {...}
heap_only_please(params) {...}
public:
static heap_only_please* create(params)
{
return new heap_only_please(params);
}
void Release() { delete this; }
// Want refcounting? Put it in Release!

};
Goran.