【C++】動態內存管理

【C++】

動態內存管理:

C語言中:標準庫的函數 malloc/free

void Test1()
{
    int* p1 = (int*)malloc(sizeof(int) * 4);
    free(p1);
    p1 = NULL;
    int* p2 = (int*)calloc(4, sizeof(int));
    int* p3 = (int*)realloc(p2, sizeof(int) * 6);
    //p2開闢的內存空間被修改爲p3/p2已被釋放
    free(p3);
    p3 = NULL;
}

C++中:c++操作符 new/delete

void Test2()
{
    int* p1 = new int;//p1指向一個int型的空間/動態分配4個字節
    int* p2 = new int(3);//初始化爲3
    int* p3 = new int[3];//開闢了3個int型空間/動態分配12個字節
    delete p1;
    delete p2;
    delete[] p3;//匹配使用 防止內存泄漏
}

區別與聯繫:

  • 都是動態內存管理的入口
  • malloc/free 是C/C++標準庫的函數,new/delete 是C++操作符
  • malloc/free只是動態分配內存和釋放空間,new/delete 還會調用構造/析構函數
  • malloc/free使用時要自己計算空間大小,返回void*指針,使用指針時需自己強轉;new會自己計算空間大小,返回相應的類型的指針

內存管理

這裏寫圖片描述

深入瞭解new/delete & new[]/delete[]

  • new 會調用operator new函數,還會調用構造函數進行初始化
  • delete 會調用operator delete函數,調用析構函數進行釋放
  • new[]會調用operator new[]函數,會調用N次構造函數初始化
  • delete[]調用operator delete[]函數,會調用N次析構函數
class Array
{
public:
    Array(size_t size = 1)
        :_a(0)
        , _size(size)
    {
        cout << "Array" << endl;
        if (_size > 0)
        {
            _a = new int[_size];
        }
    }
    ~Array()
    {
        cout << "~Array" << endl;
        if (_a)
        {
            delete[] _a;
            _a = 0;
            _size = 0;
        }
    }
private:
    int* _a;
    size_t _size;
};
int main()
{
    Array* p1 = new Array;
    delete p1;
    Array* p2 = new Array[2];
    delete[] p2;
    return 0;
}

void* operator new(size_t size) 這些函數並沒有重載new和delete,我們不能對new/delete進行表達式重定義
- 這些函數也是通過使用molloc來開闢空間,通過free來釋放空間

深度剖析

這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章