C++动态空间的申请


为什么C++的动态分配是new和delete?

因为malloc 函数和对应的free函数不能调用构造函数和析构函数,这破坏了空间分配、初始化的功能。所以引入了new和delete。

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

堆空间不伴随函数动态释放,程序员要自主管理

[cpp]
  1. //============================================================================   
  2. // Name        : main.cpp   
  3. // Author      : ShiGuang   
  4. // Version     :   
  5. // Copyright   : sg131971@qq.com   
  6. // Description : Hello World in C++, Ansi-style   
  7. //============================================================================   
  8.   
  9. #include <iostream>   
  10. #include <string>   
  11. using namespace std;  
  12.   
  13. class aa  
  14. {  
  15. public:  
  16.     aa(int a = 1)  
  17.     {  
  18.         cout << "aa is constructed." << endl;  
  19.         id = a;  
  20.     }  
  21.     ~aa()  
  22.     {  
  23.         cout << "aa is completed." << endl;  
  24.     }  
  25.     int id;  
  26. };  
  27.   
  28. aa & m()  
  29. {  
  30.     aa *p = new aa(9);  
  31.     delete p;  
  32.     return (*p);  
  33. }  
  34.   
  35. int main(int argc, char **argv)  
  36. {  
  37.     aa & s = m();  
  38.     cout << s.id;// 结果为随机数,表明被释放   
  39. }  
  • 1
  • 2
  • 下一页

相关内容