gamesmathematical programsotherabout author

Memory C++ library

ru

download source code

The library is usefull for multidimensional arrays. It's realized as C++ template class which is automatically allocate and free dynamic memory. The class can be use for one two or three dimensional arrays.

The basic advantages are:

Simple creation of two and three dimensional arrays

extern int x;
extern int y;
double*p=new double[x][y];//error (need to write cycles for memory allocation)

extern int x;
extern int y;
Memory<double>p(x,y);//ok!

Automatic freeing memory

Sample of difficult-to-locate error

double*p=new double[1000];
...
throw "some error";//memory leak
...
delete[]p;

In the sample memory should be freed before throw statement. It's not need to do it if you use Memory class.

Memory<double> m(1000);
...
throw "some error";
...
//the memory will be freed even if exception is occured

Bounds checker

Sample of difficult-to-locate error

double* m = new double[10*10];
double*p=m.begin();  
...
int k=10;
...
double val=m[k*k];//unpredictable result

When one uses memory class the exception is occured.

Memory<double> m(10,10);
double*p=m.begin();  
...
int k=10;
...
double val=m(k,k);//out of bound exception occurs
double val=m[k*k];//out of bound exception occurs

Data is one dimentional array, so one can access to two or three dimensional array as one dimensional

Memory<int> m(3,2);//create two dimensional array
int i,j,k;
//access as one dimensional array
for(i=0;i<m.size();i++){
 m[i]=i;//alternative form "m(i)=i"
}

//access as two dimensional array
for(i=k=0 ; i<m.sizex() ; i++){
 for(j=0 ; j<m.sizey() ; j++){
  m( i , j )=k++; 
  }
}
 
//access using pointer
int*p;
for(k=0,p=m.begin() ; p!=m.end() ; *p++=k++ );

Memory reallocation

Memory<int> m(3,2);//create two dimensional array
int k,*p;
for(k=0,p=m.begin() ; p!=m.end() ; *p++=k++ );
...
//m needs as one dimensional array
m.init(10);
for(k=0,p=m.begin() ; p!=m.end() ; *p++=k++ );
...