為什麼C++的動態分配是new和delete?
因為malloc 函數和對應的free函數不能調用構造函數和析構函數,這破壞了空間分配、初始化的功能。所以引入了new和delete。
//============================================================================
// Name : main.cpp
// Author : ShiGuang
// Version : www.2cto.com
// Copyright : [email protected]
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
#include <string>
using namespace std;
class aa
{
public:
aa(int a = 1)
{
cout << "aa is constructed." << endl;
id = a;
}
int id;
~aa()
{
cout << "aa is completed." << endl;
}
};
int main(int argc, char **argv)
{
aa *p = new aa(9);
cout << p->id << endl;
delete p;
cout << "" << endl;
aa *q = (aa *) malloc(sizeof(aa));
cout << q->id << endl;//隨機數 表明構造函數未調用
free(q);//析構函數未調用
}
運行結果:
aa is constructed.
9
aa is completed.
3018824
堆空間不伴隨函數動態釋放,程序員要自主管理
//============================================================================
// Name : main.cpp
// Author : ShiGuang
// Version :
// Copyright : [email protected]
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
#include <string>
using namespace std;
class aa
{
public:
aa(int a = 1)
{
cout << "aa is constructed." << endl;
id = a;
}
~aa()
{
cout << "aa is completed." << endl;
}
int id;
};
aa & m()
{
aa *p = new aa(9);
delete p;
return (*p);
}
int main(int argc, char **argv)
{
aa & s = m();
cout << s.id;// 結果為隨機數,表明被釋放
}
運行結果:
aa is constructed.
aa is completed.
4984904
函數內部的申請空間要及時釋放,否則容易造成內存重復申請和內存迷失。
//============================================================================
// Name : main.cpp
// Author : ShiGuang
// Version :
// Copyright : [email protected]
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
#include <string>
using namespace std;
class aa
{
public:
aa(int a = 1)
{
cout << "aa is constructed." << endl;
id = a;
}
~aa()
{
cout << "aa is completed." << endl;
}
int id;
};
void p()
{
aa *s = new aa[9999];
}
int main(int argc, char **argv)
{
for (;;)
p();
return 0;
}
摘自 sg131971的學習筆記