5、C++ 动态内存分配的异常处理:
- // memory.cpp : 定义控制台应用程序的入口点。
- //2011/10/13 by wallwind
- #include "stdafx.h"
- #include <iostream>
- #include <sstream>
- #include <string>
- using namespace std;
- int _tmain(int argc, _TCHAR* argv[])
- {
- int ii;
- double *ptr[5000000];
- try
- {
- for( ii=0; ii < 5000000; ii++)
- {
- ptr[ii] = new double[5000000];
- }
- }
- catch ( bad_alloc &memmoryAllocationException )
- {
- cout << "Error on loop number: " << ii << endl;
- cout << "Memory allocation exception occurred: "
- << memmoryAllocationException.what()
- << endl;
- }
- catch(...)
- {
- cout << "Unrecognized exception" << endl;
- }
- return 0;
- }
运行:
-
观察系统约束: ulimit -a
-
设置系统约束: ulimit -m 100
-
以很小的优先权运行: nice -n 19 AllocNewTest
6、C++ Virtual Destructors
- // memory.cpp : 定义控制台应用程序的入口点。
- //2011/10/13 by wallwind
- #include "stdafx.h"
- #include <iostream>
- #include <sstream>
- #include <string>
- using namespace std;
- class Base
- {
- public:
- Base(){};
- virtual ~Base(){ cout << "Base class destructor called" << endl; }
- };
- class Derived : public Base
- {
- public:
- Derived(){};
- ~Derived(){ cout << "Derived class destructor called" << endl; }
- };
- int _tmain(int argc, _TCHAR* argv[])
- {
- Base *ptr = new Derived();
- delete ptr;
- return 0;
- }
运行结果:

图七
注意:
- 如果删除操作符被应用在基类中,并且其析构函数并不是虚函数,这将会引起内存泄露,因为只有基类的内存被释放掉。
- 基类的析构函数不是纯虚函数,将不能被作为基类而实现。
- 类的析构函数可以不是virtual
