本文介绍了 MFC 如何对三种典型内存分配执行帧分配和堆分配:
字节数组的分配
在帧上分配字节数组
定义数组,如以下代码所示。 当数组变量退出其范围时,将自动删除该数组及其内存回收。
{ const int BUFF_SIZE = 128; // Allocate on the frame char myCharArray[BUFF_SIZE]; int myIntArray[BUFF_SIZE]; // Reclaimed when exiting scope }
在堆上分配字节数组(或任何基元数据类型)
将
new
运算符与此示例中显示的数组语法一起使用:const int BUFF_SIZE = 128; // Allocate on the heap char* myCharArray = new char[BUFF_SIZE]; int* myIntArray = new int[BUFF_SIZE];
从堆解除分配数组
按如下所示使用
delete
运算符:delete[] myCharArray; delete[] myIntArray;
数据结构的分配
在帧上分配数据结构
定义结构变量,如下所示:
struct MyStructType { int topScore; }; void MyFunc() { // Frame allocation MyStructType myStruct; // Use the struct myStruct.topScore = 297; // Reclaimed when exiting scope }
当结构退出其范围时,将回收结构占用的内存。
在堆上分配数据结构
用于
new
在堆上分配数据结构并delete
解除分配它们,如以下示例所示:// Heap allocation MyStructType* myStruct = new MyStructType; // Use the struct through the pointer ... myStruct->topScore = 297; delete myStruct;
对象分配
在帧上分配对象
按如下所示声明对象:
{ CMyClass myClass; // Automatic constructor call here myClass.SomeMemberFunction(); // Use the object }
当对象退出其范围时,将自动调用对象的析构函数。
在堆上分配对象
new
使用返回指向对象的指针的运算符在堆上分配对象。delete
使用运算符删除它们。以下堆和帧示例假定
CPerson
构造函数不采用任何参数。// Automatic constructor call here CMyClass* myClass = new CMyClass; myClass->SomeMemberFunction(); // Use the object delete myClass; // Destructor invoked during delete
如果构造函数的参数
CPerson
是指向的指针char
,则帧分配的语句为:CMyClass myClass("Joe Smith");
堆分配的语句为:
CMyClass* myClass = new CMyClass("Joe Smith");