Topic: Realloc and C++


Author: lewis@sophists.com (Lewis G. Pringle)
Date: Thu, 22 Oct 1992 16:27:34 GMT
Raw View
In article <1992Oct21.105510.249@enpc.fr> bouaziz@asterix.enpc.fr (Laurent BOUAZIZ) writes:
>I'm quite new to C++ and I would like to know if there is a way to "realloc"ate
>in C++. Does "new" have a special syntax to do this?

I assume you mean to reallocate an array of C++ objects. Anything else,
and there is no problem - you can use malloc/free/realloc.

I know of no realloc mechanism in ARM, or StandardC++. However, libg++ 2.2
has a function of the form (in new.h)
inline void *operator new(size_t size, void *ptr, size_t new_len)
{
  return realloc(ptr, new_len * size);
}
I'm not quite sure if, or how this works.


As far as I know, the only safe/portable way to do a realloc is to use manual
construction, and destruction of objects. Here is a code fragment:

template <class T> void Array<T>::SetSlotsAlloced (size_t slotsAlloced)
{
  if (fSlotsAllocated != slotsAlloced) {
    if (slotsAlloced == 0) {
      if (fItems) { free (fItems); }
      fItems = Nil;
    }
    else {
      if (fItems == Nil) {
        fItems = (T*) malloc (sizeof (T) * slotsAlloced);
      }
      else {
        fItems = (T*) realloc (fItems, sizeof (T) * slotsAlloced);
      }
     }
     fSlotsAllocated = slotsAlloced;
   }
}

template <class T> void Array<T>::SetLength (size_t newLength, T fillValue)
{
  if (newLength > fSlotsAllocated) {
    SetSlotsAlloced (newLength);
  }
  register T* cur = &fItems[fLength];
  register T* end = &fItems[newLength];
  if (newLength > fLength) {
    Assert (cur < end);
    do {
      new (cur) T (fillValue); // this is how to manually construct items
    } while (++cur < end);
  }
  else {
    Assert (cur >= end);
    while (cur-- > end) {
      cur->T::~T ();  // This is how to destroy items
    // NB: This breaks CFront 2.1 based compilers.
    // If your curious, I have a hack to trick them
    }
  }
  fLength = newLength;
}

Note that in SetSlotsAlloced - the only place you allocate the array, treat
the array as an array of bytes of the appropriate length, and in SetLength(),
you manually construct and destruct items off the end.

BTW, this has another very nice side effect, which is that it lifts the C++
restriction on arrays that they must take a default CTOR - here they do not -
you may pass in a fill value when increasing the length (of course you might
overload SetLength () to not take a fill value and use a default CTOR for T
if you like).



--
Reading peoples signatures is a real waste of time.

lewis@sophists.com                                  (Lewis Gordon Pringle, Jr.)




Author: bouaziz@asterix.enpc.fr (Laurent BOUAZIZ)
Date: 21 Oct 92 10:55:10 GMT
Raw View
I'm quite new to C++ and I would like to know if there is a way to "realloc"ate
in C++. Does "new" have a special syntax to do this?

 Thank You.