内存管理:示例

本文介绍 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 [] myCharArray;
    delete [] myIntArray;
    

数据结构中分配

框架上分配一个数据结构。

  • 定义结构变量:

    struct MyStructType { int topScore; };
    void MyFunc()
    {
        // Frame allocation
        MyStructType myStruct;
    
        // Use the struct 
        myStruct.topScore = 297;
    
        // Reclaimed when exiting scope
    }
    

    当退出其范围时,结构占用的内存回收。

分配堆的数据结构。

  • 使用 new 分配堆和 删除 的数据结构释放它们,如下面的示例所示:

    // 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 运算符,返回指向对象的指针,此分配堆上的对象。 使用 删除 运算符来删除这些对象。

    下面的示例假定 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");
    

请参见

概念

内存管理:堆分配