From: Phil <ph...@fl...> - 2002-04-25 19:59:39
|
Thanks very much! I've rewritten the function, taking the recommendations into account. It now looks like this: template <class T> void resize_array(T *&array, int old_size, int new_size) { cerr << "resize_array called: old_size: " << old_size << " new_size: " << new_size << "\n"; if (old_size = 0) array = new T[new_size]; if (new_size == old_size) return; int items_to_copy = (new_size > old_size)?old_size:new_size; T *new_array = new T[new_size]; memcpy(new_array, array, sizeof(array[0]) * items_to_copy); delete []array; array = new_array; } template void resize_array(KeyboardEventHandler *&array, int old_size, int new_size); template void resize_array(MouseMotionEventHandler *&array, int old_size, int new_size); template void resize_array(MouseButtonEventHandler *&array, int old_size, int new_size); There's only one problem: now I'm getting errors that look like this: client_api.cpp:53: no matching function for call to `resize_array (KeyboardEventHandler *&, int &, int &)' I assume this has something to do with my use of templates, but I'm not experienced enough with them to say for sure. Thanks, Philip Bock ----- Original Message ----- From: "Stephen M.Webb" <ste...@cr...> To: "Phil" <ph...@fl...> Sent: Thursday, April 25, 2002 1:38 PM Subject: Re: [Mingw-users] Resizing arrays in C++ > On April 25, 2002 02:02 pm, you wrote: > > Thanks. I have an old reference book that came with Turbo C++ 3.0 > > which says sizeof(array) returns the number of bytes allocated, which > > is the reason I was using that. I guess I should stop using that > > book. > > Well, the book may be right. > > int array[10]; // statically bound to 10 ints > assert(sizeof(array) == 10)); > > is not the same as > > int* arrayPtr = array; // dynamically bound to the same memory > assert(sizeof(arrayPtr) == sizeof(int*)); > > > As for this delete[], it's the first I've heard about it. How > > would that statement look? I suppose something like this: > > > > delete array[]; > > > > Or do I have to include the number of elements to delete in the > > square brackets? > > int bufsize = 10; > char* buff = new char[bufSize]; > .... > delete[] buf; > > the important thing is to pair the new[] operator with the delete[] > operator, because between the two of them the number of elements of the > array are tracked. > > Note that you can overload the new and delete operators and their array > cousins for a class. Looks weird but lets you perform custom memory > allocation. > > class C > { > static void* operator new[](size_t size); > static void operator delete[](void* p, size_t); > }; > > C* cptr = new C[csize]; // calls C::operator new[](csize) > ... > delete[] cptr; // calls C::operator delete[](cptr, csize) > > -- > Stephen M. Webb > |