Path: utzoo!news-server.csri.toronto.edu!cs.utexas.edu!uunet!olivea!apple!netcom!sjsumcs!horstman From: horstman@mathcs.sjsu.edu (Cay Horstmann) Newsgroups: comp.lang.c++ Subject: Re: Why no renew Message-ID: <1991Mar3.053504.14027@mathcs.sjsu.edu> Date: 3 Mar 91 05:35:04 GMT References: <2488@bnlux0.bnl.gov> <10895@pasteur.Berkeley.EDU> Organization: San Jose State University - Math/CS Dept. Lines: 43 In article <10895@pasteur.Berkeley.EDU> jbuck@galileo.berkeley.edu (Joe Buck) writes: >[ 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? (stuff deleted) It is abundantly clear what renew should do. If the size of the renewed block is larger than the size of the current block, grow the current block (if possible) or copy the elements over with a bitwise copy to a new block, then RUN THE DEFAULT CONSTRUCTOR on the remaining (new) elements. If the renewed block is smaller, the top elements of the current block should be passed to the destructor. Note that this cannot be easily done with the array version of operator new. You must write some code like X* newptr = new X[newsize]; // runs the constructor newsize times for( int i = 0; i < oldsize; i++ ) newptr[i] = oldptr[i]; // runs X::operator= oldsize times delete[] oldptr; // runs the destructor oldsize times Clearly this is less than efficient. Contrast with a renew operator which just runs the default constructor newsize-oldsize times. I have a parametric variable array class that fakes the renew feature by allocating new char[size*sizeof(X)], then runs constructors and destructors with the placement syntax on each array element when necessary. But it doesn't work for non-class types (int's, pointers) or class types without both X::X(), X::~X() (e.g. Complex.) That is a real pain. SINCE I AM AT IT: It would be awful nice if operator new could zero out the memory when allocating arrays of integers or pointers (i.e. fill the array with the bit pattern corresponding to a logical zero.) Performance impact should be minimal, and since ints etc. don't have constructors, there is no good way for the programmer to achieve the same effect. This suggestion surely doesn't break any existing code. Cay