A
Axter
Bushido said:(skeptical) I don't know. That way seems to suck up more memory that
it should. Especially the lines where the pool is used.
One thing I certainly disagree with is the Free2DArray.
The problem with using
delete[] *Array;
is that it only deletes what ever is at Array[0]. Any other data in
in that row is still allocated. Thus, a memory leak is present at
Array[1], Array[2], etc.
There is no memory leak using that method. That's the beauty of it.
You can delete the entire array with on call to delete.
You can easily test this out by the following test program.
class foo
{
public:
foo(){cout << "foo" << endl;}
~foo(){cout << "~foo" << endl;}
};
int main(int argc, char* argv[])
{
foo ** foo_arr = Allocate2DArray<foo>(2, 3);
Free2DArray(foo_arr);
If you run the above program, you'll see six constructor calls, and six
destructor calls.
If there was a leak, there would be some missing destructor calls.
I also noticed your way used much more memory that it should. Perhaps
this is why you prefere vectors over arrays.
In your Allocate2DArray, you created
T *pool = new T [nRows * nCols];
This statment says you want to allocate (nRows * nCols) space IN EACH
ROW!
You then renamed pool curPtr. This mean pool could drop all that
allocated space at the end of Allocate2DArray and could not put it back
in Free2DArray because you used the "new" operator.
This is also incorrect. In my code I'm only doing two calls to new.
The first call creates an array of pointers.
The second call creates an array of the target type.
It uses exactly the same amount of memory space as your original code.
You can verify this via profile test.
Remember, when you do a delete, you need to do the delete on the
pointer you got back when using new. That what this code does.
There is no memory leak, and this code is much more efficient, because
it doesn't have to call new and delete over and over again for each
row.
It makes one call to new, that creates a pool of memory.
Then it iterates through the pool of memory, and assign sections that
are divided by the quantitiy of rows.
I know the code is a little hard to understand, and can be misleading
as to what it's doing, but if you run it and test it, you'll see that
it does exactly what it's suppose to do, and it does it more
efficiently.