Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

C/C++ 動態記憶體配置對決:malloc/free 與 new/delete 的差別

同樣是向系統「借」記憶體,C 與 C++ 給出的工具卻有本質上的差異。最關鍵的一點在於:C 的 malloc() 與 free() 只是單純的記憶體操作,完全不知道「物件」這回事,因此不會觸發任何建構子或解構子;而 C++ 的 new 與 delete 屬於「具備類別意識」的操作子,new 的時候會呼叫類別的建構子,delete 的時候則會呼叫解構子。

一、new/delete 與 malloc/free 的行為差異

下面用一個最小的例子把差別看清楚:

// memory.cpp : 主控台應用程式的進入點
// 2011/10/13 by wallwind
#include "stdafx.h"
#include <iostream>

using namespace std;

class SS
{
public:
    SS();
    ~SS();
private:
    int ff;
    int gg;
};

SS::SS()
{
    ff = 5;
    cout << "Constructor called" << endl;
}

SS::~SS()
{
    cout << "Destructor called" << endl;
}

int _tmain(int argc, _TCHAR* argv[])
{
    SS *ss;
    ss = new SS;    // new 操作子會呼叫建構子
    delete ss;      // delete 操作子會呼叫解構子
    return 0;
}

執行結果如圖一所示,畫面上會依序印出 Constructor called 與 Destructor called,這正是 new/delete 與 malloc/free 最直觀的分野。

務必注意:不要混用。以 malloc 配置、用 delete 釋放,或者以 new 配置、用 free 釋放,都是錯誤寫法。C++ 的 new 負責以建構子完成記憶體的初始化,delete 則負責呼叫解構子清理,兩者必須成對出現。

二、new/delete 的四大優勢

  • new/delete 會呼叫建構子與解構子,malloc/free 不會。
  • new 回傳的已是正確型別的指標,不需要強制型別轉換;malloc 回傳 void*,通常得自行轉型。
  • new/delete 是可以被覆載(overload)的操作子,malloc/free 只是函式,做不到這件事。
  • new 會依型別大小自行算出所需記憶體,不必像 malloc 那樣由呼叫端手動計算位元組數。

三、C 風格的動態記憶體配置

接著看 MallocTest.cpp 這個例子,它示範了 malloc 與 calloc 的用法:

// memory.cpp : 主控台應用程式的進入點
// 2011/10/13 by wallwind
#include "stdafx.h"
#include <iostream>

using namespace std;

typedef struct
{
    int ii;
    double dd;
} SSS;

int _tmain(int argc, _TCHAR* argv[])
{
    int kk, jj;
    char *str1 = "This is a text string";
    char *str2 = (char *)malloc(strlen(str1));

    SSS *s1 = (SSS *)calloc(4, sizeof(SSS));
    if (s1 == NULL) printf("Error ENOMEM: Insufficient memory available\n");
    strcpy(str2, str1);   // 複製一份字串

    for (kk = 0; kk < 5; kk++)
    {
        s1[kk].ii = kk;
    }
    for (jj = 0; jj < 5; jj++)
    {
        printf("Value stored: %d\n", s1[jj].ii);
    }
    free(s1);
    free(str2);
}

結果如圖二。這段程式刻意保留了原作者的寫法,實務上仍應為 str2 多留一位 '\0' 的空間,並避免對字串常數呼叫 free。

四、C 記憶體函式家族速覽

  • malloc:配置一段新的記憶體空間。
  • calloc:一次配置 N 段空間,並自動初始化為 0。
  • realloc:把已經配置好的指標重新調整大小。
  • free:透過指標把記憶體還給系統。
Copyright © Linux教程網 All Rights Reserved