构造函数和析构函数中抛出异常
文章目录 1 构造函数中抛出异常 2 析构函数中的异常 1 构造函数中抛出异常 如果构造函数中抛出异常会发生什么情况? 构造函数中抛出异常: 构造过程立即停止。 当前对象无法生成。 析构函数不会被调用。 对象所占的空间立即收回。 工程中的建议: 不要在构造函数中抛出异常。 当构造函数可能产生异常时,使用二阶构造模式。 编程实验:构造函数中的异常 # include <iostream> # include <string> using namespace std ; class Test { public : Test ( ) { cout << "Test()" << endl ; throw 0 ; } virtual ~ Test ( ) { cout << "~Test()" << endl ; } } ; int main ( int argc , char * argv [ ] ) { Test * p = reinterpret_cast < Test * > ( 1 ) ; try { p = new Test ( ) ; } catch ( . . . ) { cout << "Exception..." << endl ; } cout << "p = " << p << endl ; return 0 ; } Linux下可以使用如下工具判断是否有内存泄漏: