手机版
你好,游客 登录 注册
背景:
阅读新闻

C/C++之动态内存分配比较

[日期:2011-11-15] 来源:Linux社区  作者:wallwind [字体:大 中 小]

5、C++ 动态内存分配的异常处理: 

  1. // memory.cpp : 定义控制台应用程序的入口点。   
  2. //2011/10/13 by wallwind   
  3.   
  4. #include "stdafx.h"   
  5. #include <iostream>   
  6. #include <sstream>   
  7. #include <string>   
  8. using namespace std;  
  9.   
  10.   
  11. int _tmain(int argc, _TCHAR* argv[])  
  12. {  
  13.     int ii;  
  14.     double *ptr[5000000];  
  15.     try  
  16.     {  
  17.         for( ii=0; ii < 5000000; ii++)  
  18.         {  
  19.             ptr[ii] = new double[5000000];  
  20.         }  
  21.     }  
  22.     catch ( bad_alloc &memmoryAllocationException )  
  23.     {  
  24.         cout << "Error on loop number: " << ii << endl;  
  25.         cout << "Memory allocation exception occurred: "  
  26.             << memmoryAllocationException.what()  
  27.             << endl;  
  28.     }  
  29.     catch(...)  
  30.     {  
  31.         cout << "Unrecognized exception" << endl;  
  32.     }  
  33.     return 0;  
  34.   
  35. }  

运行:

  • 观察系统约束: ulimit -a
  • 设置系统约束: ulimit -m 100
  • 以很小的优先权运行: nice -n 19 AllocNewTest

6、C++ Virtual Destructors

  1. // memory.cpp : 定义控制台应用程序的入口点。   
  2. //2011/10/13 by wallwind   
  3.   
  4. #include "stdafx.h"   
  5. #include <iostream>   
  6. #include <sstream>   
  7. #include <string>   
  8. using namespace std;  
  9.   
  10. class Base  
  11. {  
  12. public:  
  13.     Base(){};  
  14.     virtual ~Base(){ cout << "Base class destructor called" << endl; }  
  15. };  
  16.   
  17. class Derived : public Base  
  18. {  
  19. public:  
  20.     Derived(){};  
  21.     ~Derived(){ cout << "Derived class destructor called" << endl; }  
  22. };  
  23.   
  24. int _tmain(int argc, _TCHAR* argv[])  
  25. {  
  26.     Base *ptr = new Derived();  
  27.     delete ptr;  
  28.     return 0;  
  29.   
  30. }  

运行结果:

图七

注意:

  • 如果删除操作符被应用在基类中,并且其析构函数并不是虚函数,这将会引起内存泄露,因为只有基类的内存被释放掉。
  • 基类的析构函数不是纯虚函数,将不能被作为基类而实现。
  • 类的析构函数可以不是virtual
linux
相关资讯       C++ 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款