17.37
17.38
ifstream is("test_2.txt");
char c[200];
while (!is.eof())
{
is.getline(c, 200,'\n');
cout.write(c, is.gcount());
}
一开始的版本没有设置delim,发现getline无法自动前进到下一行,折腾了好久,当getline在读取一行发生错误时(没有遇到delim,或者读取文本大小大于给定的size)就不会前进到下一行,write也是一样(输出的内容小于或大于给定的size)
17.39
fstream inOut("test_2.txt", fstream::ate|fstream::in|fstream::out);
if(!inOut){
return EXIT_FAILURE;
}
auto end_mark = inOut.tellg();
inOut.seekg(0,fstream::beg);
size_t cnt = 0;
string line;
while(inOut&&inOut.tellg() != end_mark&&getline(inOut,line)){
cnt += line.size()+1;
cout << line.size() << endl;
auto mark = inOut.tellg();
inOut.seekp(0,fstream::end);
inOut << cnt;
if(mark != end_mark)
inOut << " ";
inOut.seekg(mark);
}
inOut.seekp(0,fstream::end);
inOut<< "\n";
18.1
a.range_error 对象
b.exception 指针
会抛出一个指针而不是对象,无法捕获
18.2
v和in在异常发生后都被正确释放了,而指针p也被释放了,但是声请的int数组并没有被释放,造成内存泄露
18.3
1.将p创建为智能指针
2.将p构造成类,并在析构函数中释放声请的内存
18.4
越是继承链顶端越要写在前面
try{
}
catch (overflow_error eobj) {
}
catch (const runtime_error & re) {
}
catch(exception){
}
18.5
try{
}
catch (const length_error& le) {
cout << le.what();
abort();
}
catch (const out_of_range& oor) {
cout << oor.what();
abort();
}
catch (const invalid_argument& ia) {
cout << ia.what();
abort();
}
catch (const domain_error& de) {
cout << de.what();
abort();
}
catch (const range_error& re) {
cout << re.what();
abort();
}
catch (const underflow_error& ue) {
cout << ue.what();
abort();
}
catch (const overflow_error& ue) {
cout << ue.what();
abort();
}
catch (const runtime_error & re) {
cout << re.what();
abort();
}
catch (const logic_error& ue) {
cout << ue.what();
abort();
}
catch (const bad_cast& bc) {
cout << bc.what();
abort();
}
catch (const bad_alloc& ba) {
cout << ba.what();
abort();
}
catch(const exception& e){
cout << e.what();
abort();
}
18.6
a. throw &exceptionType();
b. throw exception(); // 任何异常都能不火
c.throw EXCPTYPE;
18.7
BlobPtr()try:curr(0){
}catch(const std::bad_alloc & e ){
}
Blob(initializer_list<T> il)try{
}catch(const std::bad_alloc& e){
};
18.8