ISArray






3.67/5 (3 votes)
May 3, 2000

86120

446
A simple templated array class.
Introduction
ISArray
is a simple array class template. It is especially useful when you need to dynamically allocate arrays of objects in functions that have many possible return points. Instead of having to call delete [] pArray
at each return point, you can let the ISArray destructor handle it for you.
Example
int MyFunction() { // declare an array of 256 chars called "charArray" ISArray < char > charArray(256); // init to 0's charArray.Fill( (char)0 ); // get a pointer to the start of the array char *pArray = (char *)charArray; // lots of ugly code with lots of ways out... if (...) { for (...) { if (...) { // error! return -1; } } if (...) { // error! return -2; } else { // no error return 1; } } return 1; }
If you had allocated the array the traditional C++ way, with
char *pArray = new char[256];
or the traditional C way, using
pArray = (char *)malloc(256);
you would have had to call delete [] pArray;
or free(pArray)
at each return point. But, with ISArray
, the ISArray
destructor handles this for you. This insures against memory leaks, and makes your code much cleaner to look at. In extreme cases (such as the one we wrote it for) this class can actually cut down the size of your app, by eliminating all of the clean-up code.
In addition, ISArray
allows you to delay the allocation of the memory, instead of doing it in the ISArray
constructor. This can be very handy if the allocation is conditional. Of course, you don't have to test that the array has been allocated before deleting it, the ISArray
destructor handles this for you, too.
We've also included some handy utility functions to copy one array to another, set/get the array size, etc..
Usage
// include the header #include "ISArray.h" void func() { // declare an array - allocate in the ctor ISArray <CString> stringArray(100); // declare some arrays - allocate later ISArray <BYTE> bytes1; ISArray <BYTE> bytes2; // allocate now bytes1.SetSize(1000); bytes1.Fill(0); // copy bytes2 = bytes1; }
Remember - have fun.