|
|
|
|
|
|
|
You don't have to worry about creating or deleting the this pointer. The compiler takes care of that. |
|
|
|
|
|
|
|
|
Stray or Dangling Pointers |
|
|
|
|
|
|
|
|
One source of bugs that are nasty and difficult to find is stray pointers. A stray pointer is created when you call delete on a pointerthereby freeing the memory that it points toand later try to use that pointer again without reassigning it. |
|
|
|
|
|
|
|
|
It is as though the Acme Mail Order company moved away, and you still pressed the programmed button on your phone. It is possible that nothing terrible happensa telephone rings in a deserted warehouse. Another possibility is that the telephone number has been reassigned to a munitions factory, and your call detonates an explosive and blows up your whole city! |
|
|
|
|
|
|
|
|
In short, be careful not to use a pointer after you have called delete on it. The pointer still points to the old area of memory, but the compiler is free to put other data there; using the pointer can cause your program to crash. Worse, your program might proceed merrily on its way and crash several minutes later. This is called a time bomb, and it is no fun. To be safe, after you delete a pointer, set it to null (0). This disarms the pointer. |
|
|
|
|
|
|
|
|
Stray pointers are often called wild pointers or dangling pointers. |
|
|
|
|
|
|
|
|
|
You can use the keyword const for pointers before the type, after the type, or in both places. For example, all the following are legal declarations: |
|
|
|
|
|
|
|
|
const int * pOne;
int * const pTwo;
const int * const pThree; |
|
|
|
|
|
|
|
|
New Term: pOne is a pointer to a constant integer. The value that is pointed to can't be changed using this pointer. That means you can't write |
|
|
|
|
|
|
|
|
If you try to do so, the compiler will object with an error. |
|
|
|
|
|