练习18.1:
(a):range_error
(b):exception
抛出异常所在的地址,后续catch处理可对其进行解引用
练习18.2:
在new创建内存之后,delete释放之前发生异常,new创建的内存不能被释放,发生内存泄漏
练习18.3:
第一种:将资源的分配封装成一个类,在析构函数中delete动态内存
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
using namespace std;
class SourceManager {
public:
SourceManager(size_t sz) :p(new int[sz]) { }
~SourceManager()
{
if (p != nullptr)
{
delete p;
}
}
private:
int* p;
};
void exercise(int* b, int* e)
{
vector<int> v(b, e);
//int* p = new int[v.size()];
//替换成类管理
SourceManager(v.size());
ifstream in("ints");
//发生异常,调用析构
}
第二种:定义try语句块
void exercise(int* b, int* e)
{
vector<int> v(b, e);
int* p = new int[v.size()];
try {
ifstream in("ints");
}
catch(...) {
delete p;
}
}