Mail Archives: djgpp/1999/11/26/14:37:55
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 -