最近在学习C++的过程中,发现指针以及new和delete的使用遍布全书,可见其重要性。在学习了一个阶段之后,总结一下new和delete的用法,指针还没有摸透,待日后总结。
new和delete是C++中的两个操作符,new用于给单个对象或者数组,结构等分配内存,在内存使用完后,用delete进行释放内存。而且是一一对应关系,有了new分配了内存,必然需要delete来释放内存,其分配和释放的必须是同一地址的内存。不然就很有可能导致内存泄漏的后果,如果内存泄漏严重,程序就极有可能崩溃。
在这里顺便介绍三个术语:
(1)联编(binding):联编是指一个计算机程序自身彼此关联(使一个源程序经过编译、连接,成为一个可执行程序)的过程,在这个联编过程中,需要确定程序中的操作调用(函数调用)与执行该操作(函数)的代码段之间的映射关系,按照联编所进行的阶段不同,可分为静态联编和动态联编。
(2)静态联编(static binding):是指在编译阶段就将函数实现和函数调用关联起来,因此静态联编也叫早绑定,在编译阶段就必须了解所有的函数或模块执行所需要检测的信息,它对函数的选择是基于指向对象的指针(或者引用)的类型。
(3)动态联编(dynamic binding):指在程序执行的时候才将函数实现和函数调用关联,因此也叫运行时绑定或者晚绑定,动态联编对函数的选择不是基于指针或者引用,而是基于对象类型,不同的对象类型将做出不同的编译结果。
然后我们假设需要编写一个程序,其中需要的数组长度无法在编译时进行确定,而需要在运行时期确定其中的值,这样就无法通过声明一个数组满足需求了。因为声明数组后,程序在编译期间将会为它分配内存,无论程序最终是否使用过数组,这个数组都占用了一定的内存,而且它不够灵活。所以在这种情况下,我们就需要使用动态联编。也是用使用new创建动态数组,在运行时分配内存。
代码实例:
#include <iostream>
int main()
{
using namespace std;
int * point = new int[3];
//int * point[3] = new int;
//This is a wrong way to difine a array
point[0] = 1;
point[1] = 2;
point[2] = 3;
cout << "point[0] is " << point[0] << "\n";
cout << "point[1] is " << point[1] << "\n";
cout << "point[2] is " << point[2] << endl; //endl is equal to "\n"
delete [] point; //free memory
return 0;
}创建动态结构和创建动态数组的方式和思想并没有太大的出入。直接上实例,在代码中分析。
struct struct1 //structure definition
{
char name[20];
float volume;
double price;
};
int main()
{
using namespace std;
struct1 * ps = new struct1; //allot memory for structure
cout << "Enter name of struct1 item: ";
cin.get(ps->name,20);
cout << "Enter volume in cubic feet: ";
cin >> (*ps).volume; //method 2 for memory access
cout << "Enter price: $";
cin >> ps -> price;
cout << "Name: " << (*ps).name << endl;
cout << "Volume: " << ps->volume << " cubic feet\n"; //method 1
cout << "Price: $" << ps->price << endl; //method 2
delete ps;
return 0;
}简单说几点和创建动态数组的不同之处:
<1>创建数组时的指针类型可以根据需求不同可以是int,char,double等等,创建结构时指针类型就只能是结构变量了,也就是上述代码中的struct1,不能任意的喜欢那个类型就上哪个了。指针方面的不同就不分析了
<2>对于创建数组,分配内存和释放内存时都有一个[],但是在结构中,就没有这个[]了。
动态创建对象时,只需指定其数据类型,不必为该对象命名,new表达式返回指向新创建对象的指针,我们通过该指针来访问此对象。
int main()
{
using namespace std;
int nights = 1001;
int * pt = new int; //allocate space for an int
*pt = 1001; //store a value there
cout << "nights value = ";
cout << nights << ": location " << &nights << endl;
cout << "int ";
cout << "value = " << *pt << ": location = " << pt << endl;
double * pd = new double; //allocate space for a double
*pd = 10000001.0; //store a value there
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;
}最后简单提一下这段代码中的nights变量和pd指针的值都存放在栈(stack)中,而用new分配的内存在堆(heap)或者自由存储区(free store)中。
原文:http://blog.csdn.net/wzqnls/article/details/41578375