C++进阶--new 和 delete
一.基本用法
1.使用new分配内存
格式:
typeName * pointer_name = new typeName;# example
int * pt = new int;
- new int 告诉程序需要储存 int 的内容,new 运算符将根据类型 int 来确定需要多少个字节的内存,然后找到这样的内存,并返回其地址;
- 然后将地址赋给 pn指针,pn 指针被声明为指向 int 的指针;
- 现在,与普通指针一样,pn 是地址, *pn 是储存在那里的值;
2.使用delete释放内存
格式:
int * ps = new int;
...
delete ps;
这将释放 ps 指向的内存,但不会删除指针 ps 本身;
3.使用new创建动态数组
静态联编:在编译时就给数组分配内存;
动态联编:在运行阶段,如果需要使用数组,则创建它;否则不创建;
使用new 可以创建动态数组;
格式:
typeName * pointer_name = new typeName [num_elements];# example
int * pt = new int [10];
- 在类型名后面加上方括号 [],这将创建 10 个 int 元素的数组;
- new 运算符将返回第一个元素地址,并将地址赋给指针 pt;
释放:
delete [] pt;
- 注意 :new 带 [],则 delete 必须带;否则,必须不带;
使用:
- 访问第 i 个元素,直接 pt[i],这点不同于普通指针 *(p+i);
- 修改指针指向,与普通指针一样: pt = pt + 1;
4.使用new创建动态结构
示例:
// newstrct.cpp -- using new with a structure
#include <iostream>
struct inflatable // structure definition
{char name[20];float volume;double price;
};
int main()
{using namespace std;inflatable * ps = new inflatable; // allot memory for structurecout << "Enter name of inflatable item: ";cin.get(ps->name, 20); // method 1 for member accesscout << "Enter volume in cubic feet: ";cin >> (*ps).volume; // method 2 for member accesscout << "Enter price: $";cin >> ps->price;cout << "Name: " << (*ps).name << endl; // method 2cout << "Volume: " << ps->volume << " cubic feet\\n"; // method 1cout << "Price: $" << ps->price << endl; // method 1delete ps; // free memory used by structure// cin.get();// cin.get();return 0;
}
(1)首先需要创建一个结构,然后使用new为这个结构申请内存:
struct inflatable // structure definition
{char name[20];float volume;double price;
};inflatable * ps = new inflatable;
(2)访问结构成员
如果结构标识符是结构名,则使用句点运算符访问成员:
struct inflatable // structure definition
{char name[20];float volume;double price;
};
inflatable things;things.price = 0;
如果结构标识符是指针,则使用箭头运算符访问成员:
struct inflatable // structure definition
{char name[20];float volume;double price;
};
inflatable things;
inflatable * pt = &things;pt->price = 0;
显然,在new创建结构时,返回的是一个指针,因此访问应该使用箭头:
cin.get(ps->name, 20);
也可以使用如下方式访问:
cin >> (*ps).volume;
因为 ps 是指向结构的指针,所以 *ps 就是被指向的值(结构本身),所以 (*ps).volume 就是结构 volume 成员。