為什麼C++的動態分配是new和delete?
因為malloc 函數和對應的free函數不能調用構造函數和析構函數,這破壞了空間分配、初始化的功能。所以引入了new和delete。
[cpp]
- //============================================================================
- // 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;
- }
- 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);//析構函數未調用
- }
運行結果:
[cpp]
- aa is constructed.
- 9
- aa is completed.
-
- 3018824
堆空間不伴隨函數動態釋放,程序員要自主管理
[cpp]
- //============================================================================
- // 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;// 結果為隨機數,表明被釋放
- }