Path: utzoo!attcan!uunet!aplcen!uakari.primate.wisc.edu!zaphod.mps.ohio-state.edu!usc!cs.utexas.edu!milano!cadillac!vaughan@mcc.com From: vaughan@mcc.com (Paul Vaughan) Newsgroups: comp.lang.c++ Subject: Re: Objective suicide Message-ID: <9299@cadillac.CAD.MCC.COM> Date: 29 Jun 90 14:58:35 GMT References: <685@dyndata.UUCP> <276@taumet.com> Sender: news@cadillac.CAD.MCC.COM Reply-To: vaughan@mcc.com (Paul Vaughan) Organization: MCC VLSI CAD Program Lines: 48 In-reply-to: steve@taumet.com (Stephen Clamage) From: steve@taumet.com (Stephen Clamage) In article <685@dyndata.UUCP> dan@dyndata.UUCP (Dan Everhart) writes: >Is it kosher for an object to delete itself? To wit: > >class Obj > { > /* ... */ > void Suicide () { /* ... */ delete this; } > /* ... */ > } Yes, but do be careful, as noted in your full example. I have done this in a class destructor, but would not do it in a normal member function. After the delete, there is no guarantee that the class data makes any sense, and in particular that the virtual table is intact! So a later destructor may try to operate with garbage. This is a particular worry with virtual destructors when the virtual table is trashed. I'm having trouble making sense out of this. One reason to have objects destruct themselves is for referencing counting, eg. void Foo::UnRef() { count -= 1; if(!count) delete this; } Of course it's important that the code (object, whatever) that thought it had a reference not use the pointer after calling UnRef. Also, it's important that you don't execute anything that needs object data in the UnRef function after you delete this. Other than these considerations, I'm not aware of any reason not to delete this from a regular member function. You would clearly never want to do this Foo::~Foo() { . . . delete this; } First, it's already being deleted, second it would cause double deallocation. I'm assuming that's not what you meant, but that's what it sounded like. Paul Vaughan, MCC CAD Program | ARPA: vaughan@mcc.com | Phone: [512] 338-3639 Box 200195, Austin, TX 78720 | UUCP: ...!cs.utexas.edu!milano!cadillac!vaughan