一、使用new来分配内存
以下代码演示了如何将new用于两种不同的类型。
#include<iostream>
using namespace std;
int main()
{
int nights = 1001;
int* pt = new int;
*pt = 1001;
cout << "nights value = ";
cout << nights << ":location " << &nights << endl;
cout << "int";
cout << "value = " << *pt << ": location = " << pt << endl;
double* pd = new double;
*pd = 10000001.0;
cout << " double ";
cout << "value = " << *pd << ": location = " << pd << endl;
cout << "location of pointer pd: " << &pd << endl;
cout << "size of *pt = " << sizeof(*pt) << endl;
cout << "size of pd = " << sizeof pd;
cout << ": size of *pd = " << sizeof(*pd) << endl;
return 0;
}
1、学习使用new来分配内存之前要了解指针的用法。
2、指针真正的勇武之地在于,在运行阶段分配未命名的内存以存储内存;
在c语言中,可以用库函数malloc()来分配内存;在c++中仍然可以这样做,但c++还有更好的方法——new运算符。
二、使用delete释放内存
int * ps = new int;
. . .
delete ps;
1、只能用delete来释放使用new分配的内存。然而,对空指针使用delete是安全的。
2、养成良好的代码习惯,当创建new时最好同时敲出delete用来释放。
三、使用new来创建动态数组
#include<iostream>
using namespace std;
int main()
{
double* p3 = new double[3];
p3[0] = 0.2;
p3[1] = 0.5;
p3[2] = 0.8;
cout << "p3[1] is " << p3[1] << ".\n";
p3 = p3 + 1;
cout << "Now p3[0] is " << p3[0] << " and ";
cout << "p3[1] is " << p3[1] << ".\n";
p3 = p3 - 1;
delete[] p3;
return 0;
}
1、使用new[ ]为数组分配内存,则应使用delete[ ]来释放。
2、使用new[ ]为一个实体分配内存,则应使用delete(没用方括号)来释放。