天天看點

深入了解new/delete

c語言中提供了malloc 和free 兩個系統函數,完成對堆記憶體的申請和釋放。而c++則提供了兩關鍵字 new 和delete ;

new/new[]用法:
開辟單變量位址空間
  • int *p = new int; //開辟大小為sizeof(int)空間
  • int *a = new int(5); //開辟大小為sizeof(int)空間,并初始化為5

開辟數組空間

  • 一維: int *a = new int[100]{0};//開辟一個大小為100的整型數組空間 

int *p = new int[5]{NULL}

  • 二維: int (*a)[6] = new int[5][6]
  • 三維: int (*a)[5][6] = new int[3][5][6]
  • 四維維及其以上:依此類推.
delete /delete[]用法:
1. int *a = new int;
   delete a;   //釋放單個int的空間
2.int *a = new int[5];
   delete []a; //釋放int數組空間
           

綜合用法:

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <typeinfo>

using namespace std;
int main()
{
    int *p = new int(5);
    cout<<*p<<endl;
     delete p;

    char *pp = new char[10];
    strcpy(pp,"china");
    cout<<pp<<endl;
    delete []pp;

    string *ps = new string("china");
    cout<<*ps<<endl; //cout<<ps<<endl;
    delete ps;

    char **pa= new char*[5];
    memset(pa,0,sizeof(char*[5]));
    pa[0] = "china";
    pa[1] = "america";
    char **pt = pa;
    while(*pt)
    {
        cout<<*pt++<<endl;
    }

    delete []pt;

    int (*q)[3] = new int[2][3];
    for(int i=0; i<2; i++)
    {
        for(int j=0; j<3; j++)
        {
            q[i][j] = i+j;
        }
    }

    for(int i=0; i<2; i++)
    {
        for(int j=0; j<3; j++)
        {
            cout<<q[i][j];
        }
        cout<<endl;
    }

    delete []q;

    int (*qq)[3][4] = new int [2][3][4];

    delete []qq;

}
           

注意事項:

1,new/delete 是關鍵字,效率高于malloc和free.

2,配對使用,避免記憶體洩漏和多重釋放。

3,避免,交叉使用。比如malloc申請的空間去delete,new出的空間被free;