Memory has mainly two parts: heap(堆) and stack(栈).
1. anything related to new: heap memory use
for example: int * a = new int[ 10 ];
class A; A * a = new A;
2. otherwise it is stack memory use.
for example: int a[20];
A a ;
note that here (A)a sits on stack and may have pointers which point to heap if there
are dynamically memory allocations in the constructor.
Using new means dynamically allocating heap(堆) memory to variables. One of the main
reasons is that the sizes of many variables are often unknown in compiling time.
Their memory use has to be determined in running time. Therefore, new has to be used.
Note that on Windows stack(栈) memory is limited. Heap memory access can be slower than
stack memory access because the data in stack memory is together. The data in heap
memory may be separated(think of new and delete).
One of the main disadvantages of using new is that in pure C++ code it is the responsibility
of users to clean heap memory(delete pointer) up. If users do not do it, there is memory
leak. If users do it twice(duplicate delete), their code will crash. I normally work this way to
avoid memory leak and duplicate delete: after I use new to a pointer, I write delete this pointer
immediately at the right spot before this pointer is used anywhere. In this way, I never forget
to clean my heap memory. Also, I do this only once. Therefore, duplicate delete can be prevented.
Memory leak is not hard to detect and fix. Valgrind is a good free tool for this on Linux.
Run Valgrind to your code regularly to check memory problems.
Note that in Qt all GUI components have to be created by new because of garbage collection
and do not need to be cleaned. It is same as Java. Qt is much quicker than Java.
One typical delete error:
double * a = new double[ 10 ];
delete a; a = NULL;
It should be:
delete[] a; a = NULL;
For a dynamic array of primitive variables(float, int, double etc.), delete[] is required to clean heap memory.
After a pointer is deleted, always assign NULL to the pointer. Otherwise, the code will crash if it is deleted
again(duplicate delete) since it still points to the same location(called dangled pointer) after it is deleted.
If this pointer is assigned with NULL, nothing happens when a NULL pointer is deleted.
[ 此帖被steinlee在2010-03-04 14:45重新编辑 ]