Self destructing object?

Started by
3 comments, last by samgzman 20 years, 2 months ago
Is it possible to have an object call its own destructor? would i just call ~ClassName();?
Advertisement
yes

You can just call
delete pTomyself;

it can be very useful!

Cheers
Chris
CheersChris
An example from COM: All COM objects implement the functions AddRef() and Release(). These allow reference counting. Whenever a COM pointer is copied and used by someone else, they call AddRef(), and the internal counter is incremented. Whenever someone is done with a COM object pointer, they call Release(), and the internal counter is decreased. If it becomes zero, then the object deletes itself. It might look a bit like this:
unsigned long SomeObject::Release(){  --mRefCount;  if (mRefCount == 0)  {    delete this;    return 0;  }  else  {    return mRefCount;  }}  


[Edit - forgot "SomeObject::" part of the function definition. Doh!]

[edited by - Agony on February 6, 2004 3:29:36 PM]
"We should have a great fewer disputes in the world if words were taken for what they are, the signs of our ideas only, and not for things themselves." - John Locke
perfect... thank u
Yeah it''s possible.

But you don''t say "~ClassName()" or "delete pToMyself;" Just write "delete this;"

As you can imagine, there are are dangers. This faq entry does a good job of summing up those dangers.

This topic is closed to new replies.

Advertisement