📜  异常处理和对象销毁|套装1

📅  最后修改于: 2021-05-30 07:34:57             🧑  作者: Mango

预测以下C++程序的输出。

#include 
using namespace std;
  
class Test {
public:
  Test() { cout << "Constructing an object of Test " << endl; }
  ~Test() { cout << "Destructing an object of Test "  << endl; }
};
  
int main() {
  try {
    Test t1;
    throw 10;
  } catch(int i) {
    cout << "Caught " << i << endl;
  }
}

输出:

Constructing an object of Test
  Destructing an object of Test
  Caught 10

引发异常时,将在catch块被执行之前自动调用对象的析构函数(其作用域以try块结尾)。这就是为什么上面的程序在“捕获到10”之前打印“破坏测试的对象”的原因。

从构造函数引发异常时会发生什么?考虑以下程序。

#include 
using namespace std;
  
class Test1 {
public:
  Test1() { cout << "Constructing an Object of Test1" << endl; }
  ~Test1() { cout << "Destructing an Object of Test1" << endl; }
};
  
class Test2 {
public:
  // Following constructor throws an integer exception
  Test2() { cout << "Constructing an Object of Test2" << endl; 
            throw 20; }
  ~Test2() { cout << "Destructing an Object of Test2" << endl; }
};
  
int main() {
  try {
    Test1 t1;  // Constructed and destructed
    Test2 t2;  // Partially constructed
    Test1 t3;  // t3 is not constructed as this statement never gets executed
  } catch(int i) {
    cout << "Caught " << i << endl;
  }
}

输出:

Constructing an Object of Test1
  Constructing an Object of Test2
  Destructing an Object of Test1
  Caught 20

仅针对完全构造的对象才调用析构函数。当对象的构造函数引发异常时,不会调用该对象的析构函数。

作为一项专长,请预测以下程序的输出。

#include 
using namespace std;
  
class Test {
  static int count;
  int id;
public:
  Test() {
    count++;
    id = count;
    cout << "Constructing object number " << id << endl;
    if(id == 4)
       throw 4;
  }
  ~Test() { cout << "Destructing object number " << id << endl; }
};
  
int Test::count = 0;
  
int main() {
  try {
    Test array[5];
  } catch(int i) {
    cout << "Caught " << i << endl;
  }
}
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”