delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1999/11/26/14:37:55

From: broeker AT acp3bf DOT knirsch DOT de (Hans-Bernhard Broeker)
Newsgroups: comp.os.msdos.djgpp
Subject: Re: realloc... how to do it in C++?
Date: 26 Nov 1999 18:50:22 +0100
Organization: RWTH Aachen, III. physikalisches Institut B
Lines: 33
Message-ID: <81mh8u$795@acp3bf.knirsch.de>
References: <19991126143909 DOT 7168 DOT rocketmail AT web125 DOT yahoomail DOT com>
NNTP-Posting-Host: acp3bf.physik.rwth-aachen.de
X-Trace: nets3.rz.RWTH-Aachen.DE 943638627 26134 137.226.32.75 (26 Nov 1999 17:50:27 GMT)
X-Complaints-To: abuse AT rwth-aachen DOT de
NNTP-Posting-Date: 26 Nov 1999 17:50:27 GMT
X-Newsreader: TIN [version 1.2 PL2]
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp
Reply-To: djgpp AT delorie DOT com

Mohamed Saad (bazramit AT yahoo DOT com) wrote:

>    In C there is a function called realloc() that
> reallocates some dynamically allocated memory!
>    my question is... How can i implement it in C++
> using new and delete?

In full generality, you can't. At least that's my understanding.
The problem is that for realloc() to work on 'new'ed storage, you'ld
need something like the following:

	object *newstorage = new object[newsize];
	for (int i=0; i<(oldsize<newsize ? oldsize : newsize); i++)
	   newstorage[i] = oldstorage[i];
        delete oldstorage;
	oldstorage = newstorage;

Minor problem: where do you get information about 'oldsize' from, if
all you have is 'oldstorage'?

But the major problem is the middle line: it assumes you can copy
objects of type 'object'. However, to my limited knowledge, that isn't
necessarily the case -- you *can* have objects without a copy
constructor and/or assignment operator that still can be new[]ed.

So, in a nutshell, you don't have a realloc() workalike in C++.  You
must use other means, then. STL containers like 'vector<T>', for
example, or you can implement 'realloc()' yourself, as shown above.
But then, that'd be equivalent to using vector<T>, I think, anyway,
so that's a wheel you shouldn't need to reinvent.
-- 
Hans-Bernhard Broeker (broeker AT physik DOT rwth-aachen DOT de)
Even if all the snow were burnt, ashes would remain.

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019