歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> C++動態空間的申請

C++動態空間的申請

日期:2017/3/1 10:30:44   编辑:Linux編程

為什麼C++的動態分配是new和delete?

因為malloc 函數和對應的free函數不能調用構造函數和析構函數,這破壞了空間分配、初始化的功能。所以引入了new和delete。

[cpp]
  1. //============================================================================
  2. // Name : main.cpp
  3. // Author : ShiGuang
  4. // Version :
  5. // Copyright : [email protected]
  6. // Description : Hello World in C++, Ansi-style
  7. //============================================================================
  8. #include <iostream>
  9. #include <string>
  10. using namespace std;
  11. class aa
  12. {
  13. public:
  14. aa(int a = 1)
  15. {
  16. cout << "aa is constructed." << endl;
  17. id = a;
  18. }
  19. int id;
  20. ~aa()
  21. {
  22. cout << "aa is completed." << endl;
  23. }
  24. };
  25. int main(int argc, char **argv)
  26. {
  27. aa *p = new aa(9);
  28. cout << p->id << endl;
  29. delete p;
  30. cout << "" << endl;
  31. aa *q = (aa *) malloc(sizeof(aa));
  32. cout << q->id << endl;//隨機數 表明構造函數未調用
  33. free(q);//析構函數未調用
  34. }
運行結果:
[cpp]
  1. aa is constructed.
  2. 9
  3. aa is completed.
  4. 3018824

堆空間不伴隨函數動態釋放,程序員要自主管理

[cpp]
  1. //============================================================================
  2. // Name : main.cpp
  3. // Author : ShiGuang
  4. // Version :
  5. // Copyright : [email protected]
  6. // Description : Hello World in C++, Ansi-style
  7. //============================================================================
  8. #include <iostream>
  9. #include <string>
  10. using namespace std;
  11. class aa
  12. {
  13. public:
  14. aa(int a = 1)
  15. {
  16. cout << "aa is constructed." << endl;
  17. id = a;
  18. }
  19. ~aa()
  20. {
  21. cout << "aa is completed." << endl;
  22. }
  23. int id;
  24. };
  25. aa & m()
  26. {
  27. aa *p = new aa(9);
  28. delete p;
  29. return (*p);
  30. }
  31. int main(int argc, char **argv)
  32. {
  33. aa & s = m();
  34. cout << s.id;// 結果為隨機數,表明被釋放
  35. }
Copyright © Linux教程網 All Rights Reserved