To free memory is very important:
Consider this:
char * pMyMemory = new char[100000];
A function, which does this, allocates 100 kb memory at the heap.
If the function would not free the memory, and your programm would often call this function, more and more memory will be allocated. At last your computer hasn't any memory left and your program will crash.
And people, who wrote C programs often forget this:
for example:
1 2 3 4 5 6 7 8
|
char * pMyMemory = new char[100000];
...
if(error) return error;
...
delete pMyMemory;
| |
If you write a class, you don't need to take much care of delete in your function, for example:
1 2 3 4 5 6
|
AllocMemory Allocation(100000); // also AllocMemory Allocation = 100000 would be correct
char * pMyMemory = Allocation.pMemory;
...
if(error) return error; // don't need to free, if the destructor of class AllocMemory does this
...
| |
But please, don't reassign your Allocation, if not neccessary, it's more tricky, than yould would think - see my post
"Are these really the basics of programming in C++ with visual studio 2008?".
Don't write later:
Allocation = AllocMemory(500);
If you want to reassign your memory, you should write:
1 2
|
delete Allocation.pMemory:
Allocation = 500;
| |
For doing this, you have to code an assignment operator "operator=".