Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!tut.cis.ohio-state.edu!ucbvax!hplabs!hp-pcd!hplsla!jima From: jima@hplsla.HP.COM (Jim Adcock) Newsgroups: comp.lang.c++ Subject: Re: multiple destructors Message-ID: <6590273@hplsla.HP.COM> Date: 2 Oct 89 19:35:51 GMT References: <1989Sep30.190719.3340@polyslo.CalPoly.EDU> Organization: HP Lake Stevens, WA Lines: 75 //>If I can have multiple constructors, why can't I have multiple destructors? /**** I believe that in the case of multiple constructors, the intent is to provide multiple ways of constructing one type of object. When you are done constructing, you always end up with the same kind of object, so there is of necessity only a need for one way to destroy it. If you don't like this, one option is to put a construction-type field in your object, and a destruction-type case statement in your destructor. [But isn't this just an attempt to encode multiple types of objects into one class?] Alternately, maybe what you're really trying to address is multiple ways of allocating space for a particular object, and thus need corresponding ways to free the space associated with an object: ****/ //the following [weak] example either uses built-in new or malloc for space. //it uses a dirty trick of initializing a field of foo in new. is there a //better way? #include#include #include #include class foo { private: char newtype; public: foo(){} public: void* operator new(size_t sz, char c='a'); void operator delete(void* vp); ~foo() {/* do something to foo*/} }; void* foo::operator new(size_t sz, char c) { foo* fp; if (c == 'a') { fp = (foo*) ::operator new(sz); } else if (c == 'm') { fp = (foo*) malloc(sz); } else { fprintf(stderr,"Error: presently only support foo::new('a' or 'm')\n"); exit(1); } fp->newtype = c; printf("foo::new('%c') @ %X\n",c,fp); return (void*) fp; } void foo::operator delete(void* vp) { foo* fp = (foo*) vp; printf("foo::delete flavor %c @ %X\n",fp->newtype, fp); if (fp->newtype == 'a') ::operator delete(vp); else if (fp->newtype == 'm') free((char*)vp); } main() { foo* foo0 = new foo; //use built-in memory allocator foo* foo1 = new('m') foo; //use malloc instead foo* foo2 = new('a') foo; //use built-in delete foo1; delete foo0; delete foo2; }