C++编程思想 第2卷 第1章 异常处理 清理 资源管理

如果异常发生,程序占用的资源都被正确地清理了吗?

构造函数里有一个特殊的问题:如果一个对象的构造函数在执行过程中抛出
异常,那么这个对象的析构函数就不会被调用。 

在编写构造函数时,程序员必须特别的仔细

困难的事情是在构造函数中分配资源
如果构造函数中发生异常,析构函数将没有机会释放这些资源
这个问题经常伴随着 悬挂 指针 naked pointer 出现

//: C01:Rawp.cpp
// From "Thinking in C++, Volume 2", by Bruce Eckel & Chuck Allison.
// (c) 1995-2004 MindView, Inc. All Rights Reserved.
// See source code use permissions stated in the file 'License.txt',
// distributed with the code package available at www.MindView.net.
// Naked pointers.
#include <iostream>
#include <cstddef>
using namespace std;

class Cat {
public:
  Cat() { cout << "Cat()" << endl; }
  ~Cat() { cout << "~Cat()" << endl; }
};

class Dog {
public:
  void* operator new(size_t sz) {
    cout << "allocating a Dog" << endl;
    throw 47;
  }
  void operator delete(void* p) {
    cout << "deallocating a Dog" << endl;
    ::operator delete(p);
  }
};

class UseResources {
  Cat* bp;
  Dog* op;
public:
  UseResources(int count = 1) {
    cout << "UseResources()" << endl;
    bp = new Cat[count];
    op = new Dog;
  }
  ~UseResources() {
    cout << "~UseResources()" << endl;
    delete [] bp; // Array delete
    delete op;
  }
};

int main() {
  try {
    UseResources ur(3);
  } catch(int) {
    cout << "inside handler" << endl;
  }
  getchar();
} ///:~


输出
UseResources()
Cat()
Cat()
Cat()
allocating a Dog
inside handler

程序的执行流程进入了UseResources的构造函数,Cat的构造函数成功地完成
了创建对象数组的三个对象
然而,在Dog::operator new()函数中抛出了一个异常 

猜你喜欢

转载自blog.csdn.net/eyetired/article/details/81569914