C++指针的constant和don't
C++使用两种memory: heap和stack。Stack存储每个函数的信息,包括instructions, variables defined in that function。如果函数1 call 函数2, 函数2的信息存到stack顶部。函数return时,它的所有信息被pop。Heap存global variables, C++允许程序员自己在heap上分配内存, 即new(), new总是返回指向分配在heap的内存的指针。程序员必须自己释放掉不再需要的内存, 即delete。
const int *p 意思是p所指向的东西是constant
int x = 17;
const int *p = &x;
x = 27; // OK
*p = 27; // error: read-only variable is not assignable
p = new int; // OK
int * const q 意思是指针q是constant
int y = 18;
int * const q = &y;
y = 28; // OK
*q = 28; // OK
q = new int; // error: read-only variable is not assignable
const int * const r 意思是both
int y = 18;
int * const q = &y;
y = 28; // OK
*q = 28; // error: read-only variable is not assignable
q = new int; // error: read-only variable is not assignable
Don't dereference uninitialized pointers
int *p; *p = 17;
// pointer p was never allocated memory. may compile, and will certainly crash
Don't dereference NULL pointers
int *p = &x; p = NULL; *p = 17; // may compile, and will certainly crash
Don't dereference deleted pointers
delete p; *p = 33;
// The memory has not been returned to the heap just yet, so 33 is stored.
Watch out for memory leaks
int *p = new int(82); p = NULL; p = new int(17);
// associated memory was never returned to the heap
不要滥用delete
int x = 55; int *p = &x; delete p;
// this memory did not come from the heap
Don't call delete twice on the same block of memroy
int *a = new int(99);
int *b = a;
delete a;
delete b;
// this compiles, but will crash