第13章 拷贝控制
第18章 用于大型程序的工具
Date: 2017-10-08
练习18.1
(a) range_error; (b) range_error;
改写后,将发生异常且程序中止。因为抛出异常时,当前块中创建的指针对象p会被销毁,而p指向的动态内存尚未被释放,造成内存泄漏。
练习18.2
异常发生后,v调用vector类的析构函数销毁,p指针被销毁但指向的内存不会被释放,输入流对象in调用ifstream类的析构函数销毁。
练习18.3
方案一、智能指针
shared_ptr<int> p(new int[v.size()], [](int *p){ delete[] p; });
方案二、类
class intPtr {
private:
int *p = nullptr;
public:
intPtr(size_t n): p(new int[n]) {}
~intPtr() { delete[] p; }
};
练习18.4
三个类的顺序反序即可
练习18.5
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
try {
//
}
catch (overflow_error e) {
cout << e.what();
abort();
}
catch (underflow_error u) {
cout << u.what();
abort();
}
catch (range_error r) {
cout << r.what();
abort();
}
catch (runtime_error r) {
cout << r.what();
abort();
} // end of one inheritance
catch (domain_error d) {
cout << d.what();
abort();
}
catch (invalid_argument i) {
cout << i.what();
abort();
}
catch (out_of_range o) {
cout << o.what();
abort();
}
catch (length_error l) {
cout << l.what();
abort();
}
catch (logic_error l) {
cout << l.what();
abort();
} // end of one inheritance
catch (bad_alloc b) {
cout << b.what();
abort();
} // end of one inheritance
catch (bad_alloc b) {
cout << b.what();
abort();
} // end of one inheritance
catch (exception e) {
cout << e.what();
abort();