HOUR 10 Creating Pointers
理解Pointer和它的用处
指针可以直接管理内存,就是学起来费劲。
把变量当成可以存储一个值的物体,int 可以存储一个数字,character可以存储一个字符,一个指针可以存储一个内存地址。
关于指针的命名,我们采用首字母小写p标志指针变量,例如pAge 或者pHeap
我们在声明指针的时候,应当对其初始化,如果声明时候不知道对其赋什么值,可以把 nullptr 赋值给它。一个指针如果不对其初始化,就成了wild pointer了,wild pointer 很危险,因为此指针指向未知区域,瞎用容易程序崩溃。
int *pAge = nullptr; //nullptr == NULL
int *pAge = 0; /
//以上两行效果上等效,但是实质上不一样
//编译器如果不支持C++14/11 使用NULL代替 nullptr或0
如果试图把一个非指针变量赋值给指针变量,编译器会报错(invalid conversion)
* 运算符只用在两个地方
- 表示这是个指针: unsigned short *pAge = nullptr;
- 表示反向引用: *pAge = 55;//把55赋值给pAge存储的地址对应的变量值
为什么要用指针?
三种情况用到指针:
- 管理heap数据
- 访问类成员变量、函数
- pass value by reference to functions
The Stack and the Heap
程序员接触的内存中的五个区域:
- Global name space
- 堆
- 寄存器
- 代码段
- 栈
局部变量和函数参数都储存在栈,代码储存在代码段,全局变量储存在全局名字空间。寄存器用于内部的指令指针、栈顶地址等。剩下的空间都给了堆。
局部变量的坏处是不持久(不到10分钟?ahah),当函数return时,局部变量就被丢弃;全局变量虽然解决了这个问题,但是容易产生bug,难以理解,不易维护。把数据放到heap中就解决了这一对矛盾。
把heap认为一大片内存空间,你可以借助指针在里面存放数据,不用具体知道内存的地址,只用指针调用即可。
stack在函数return自动清空,所有局部变量会清除,然后heap在程序终止后也不会清空,当你不需要这些数据时,手动清空即可,这也是你的责任,别占着茅坑不拉屎--文明点的术语叫做内存泄露(把用不到的数据放在heap上)。这种方式的好处是,你只能通过指针来访问变量,这就大大限制了访问。
Using the new Keyword
使用方法:
unsigned short int *pPointer; pPointer = new unsigned short int;
new出来的空间地址必须赋给同类型指针变量。
假如new不出来了,就代表heap空间不足了,此时会丢出一个异常。
为什么用了new必须要用delete?
When you have finished with your area of memory, you must call delete on the pointer, which
returns the memory to the heap. Remember that the pointer itself—as opposed to the memory it
points to—is a local variable. When the function in which it is declared returns, that pointer goes
out of scope and is lost. The memory allocated with the new operator is not freed automatically.This situation is called memory leak.
- 如果delete了两次指针,程序崩溃
- delete指针之后,要为指针赋值空指针nullptr,这时再此delete就harmless了
避免内存泄露
下面这段会造成内存泄露,第一次new的内存区域没有delete,又用这个指针new一块内存,导致原先new的区域地址丢失。
unsigned short int *pPointer = new unsigned short int; *pPointer = 7; unsigned short int *pPointer = new unsigned short int; *pPointer = 44
这是正确的示例:
unsigned short int *pPointer = new unsigned short int; *pPointer = 7; delete pPointer; unsigned short int *pPointer = new unsigned short int; *pPointer = 44
总之,牢记new与delete总是成对出现!!
Null Pointer Constant
考虑这两个函数重载:
void displayBuffer(char *); void displayBuffer(int);
在C++中,我们避免野指针的方法是为其赋值NULL 或者0 ,但是如果遇到这种函数重载就尴尬了,当主调函数使用一个null指针调用此函数时,会直接调用displayBuffer(int),因为null=0。
使用nullptr就可以避免这个尴尬,nullptr不会隐式转换为整型类型。
Code:Blocks用不了nullptr( This program must be compiled with the ––std=c++14 flag because nullptr is a new addition
to C++.),反正我用Qt。
Q&A
Q.用heap有什么好处?
- 存活时间久,即使函数return了,依旧存在
- 在heap上存object可以让我们不需要提前就确定object数目,可以在运行的时候再确定

浙公网安备 33010602011771号