Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!uunet!shelby!agate!pasteur!galileo.berkeley.edu!jbuck From: jbuck@galileo.berkeley.edu (Joe Buck) Newsgroups: comp.lang.c++ Subject: Re: Why no renew Message-ID: <10895@pasteur.Berkeley.EDU> Date: 7 Feb 91 23:17:58 GMT References: <2488@bnlux0.bnl.gov> Sender: news@pasteur.Berkeley.EDU Reply-To: jbuck@galileo.berkeley.edu (Joe Buck) Lines: 52 [ a proposal for a "renew" operator that works like realloc ] You're free to propose a "renew" operator as an extension if you want, but remember that new is not equivalent to malloc, and delete is not equivalent to free; new calls a constructor and delete calls a destructor. Often an object contains pointers to other dynamic objects, so the delete call causes other delete calls. What would renew do? Presumably you still need a destructor and a constructor call. Would it do these and then try to use the same block of allocated memory? If that's what you want, you could implement it by overloading the new and delete operators for the class where you want to get realloc()- style behavior. The idea would be this: the delete operator would keep the last block deleted, and new would try to use it if possible. Here's an example of an implementation: class MyClass { public: // other stuff void* operator new (size_t); void operator delete (void*, size_t); private: static void* lastBlock; static size_t lastBlockSize; } void* MyClass :: operator new (size_t size) { if (lastBlockSize == 0) return malloc(size); else if (lastBlockSize >= size) { lastBlockSize = 0; return lastBlock; } else { free(lastBlock); lastBlockSize = 0; return malloc(size); } } void MyClass :: operator delete (void* p, size_t size) { if (lastBlockSize > 0) free(lastBlock); lastBlock = p; lastBlockSize = size; } I think this kind of stuff can give you whatever advantages you wanted from realloc(), and it's isolated from the rest of the program. Overloading new and delete on a per-class basis means that you can tune memory allocation however you want. -- Joe Buck jbuck@galileo.berkeley.edu {uunet,ucbvax}!galileo.berkeley.edu!jbuck