Path: utzoo!utgpu!news-server.csri.toronto.edu!bonnie.concordia.ca!thunder.mcrcim.mcgill.edu!snorkelwacker.mit.edu!think.com!zaphod.mps.ohio-state.edu!usc!rutgers!orstcs!usenet! From: keffert@jacobs.cs.orst.edu (Thomas Keffer) Newsgroups: comp.lang.c++ Subject: Overloaded operator new VS. inheritance Message-ID: <1991Jan10.195541.6003@usenet@scion.CS.ORST.EDU> Date: 10 Jan 91 19:55:41 GMT Sender: @usenet@scion.CS.ORST.EDU Organization: Oregon State University, CS Dept. Lines: 69 Nntp-Posting-Host: jacobs.cs.orst.edu I've been using overloaded new and delete operators to implement a "small object pool" to speed the allocation and deallocation of small objects from the heap. I have been running into problems with inheritance and want to propose a simple language extension to deal with the problem. Here's an example: #define STASHSIZE 10 static void* stash[STASHSIZE]; // The pool of "free" objects. static short nstash = 0; // The number of objects in the pool class Small { ... public: void* operator new(size_t sz){ // If the pool is empty, use the global allocator: return nstash ? stash[--nstash] : ::new char[sz]; } void operator delete(void* b){ // If the pool is full, call the global delete operator. if(nstash>=STASHSIZE) ::delete b; else stash[nstash++] = b; } }; So what's the problem? Inheritance. If another (larger) object is inherited from class "Small", it will inherit Small's new and delete operators. The pool will be full of objects of the wrong size, resulting in an error. Because the size of the object is available to Small::operator new, I could fix this by maintaining an array of free objects, one slot for each object size (up to some certain maximum beyond which ::new is called). Given the size of the object, I pick the proper slot and return an appropriately sized object. But then what about the delete operator? The size of the object is NOT passed to Small::operator delete. I don't know where to put the recently freed object. It appears that to use overloaded new and delete operators safely you must either: 1) remember the object's size within the object itself (requiring extra memory). or 2) give the object only private constructors, disallowing inheritance. An easy solution to the problem would be to have Small::operator delete pass the size of the object --- it's known at the point of call, even for objects with virtual destructors. Comments? -tk --- Tom Keffer | uucp: ...!orstcs!rwave!keffer Rogue Wave | Internet: keffer%rwave.uucp@cs.orst.edu P.O. Box 2328 | BIX: tkeffer Corvallis, OR 97339 | (503) 745-5908