同樣是向系統「借」記憶體,C 與 C++ 給出的工具卻有本質上的差異。最關鍵的一點在於:C 的 malloc() 與 free() 只是單純的記憶體操作,完全不知道「物件」這回事,因此不會觸發任何建構子或解構子;而 C++ 的 new 與 delete 屬於「具備類別意識」的操作子,new 的時候會呼叫類別的建構子,delete 的時候則會呼叫解構子。
下面用一個最小的例子把差別看清楚:
// 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 則負責呼叫解構子清理,兩者必須成對出現。
接著看 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。