标签:
继续上一篇文章提到的构造异常话题,
第三个场景:对继承中,某个基类构造异常,而其他基类已构造成功,则构造成功的基类不会析构,由编译器负责回收
1 class B{ 2 3 public: 4 B(){ 5 age = 0; 6 cout << "construct B default" << endl; 7 throw 0;//抛出异常 8 } 9 10 ~B(){ 11 cout << "destructor B ,age=" << age << endl; 12 } 13 private: 14 int age; 15 }; 16 17 class C{ 18 public: 19 C(){ 20 //得到指定范围[m,n]的随机数:r = rand()%(n - m + 1) + m; 21 int r = rand()%(8-0)+0; 22 num = r; 23 cout << "constuctor C ,num = " << num << endl; 24 25 } 26 ~C(){ 27 cout << "destructor C, num = " << num << endl; 28 } 29 private: 30 int num; 31 }; 32 33 class D:public C, public B{ 34 35 public: 36 D(){ 37 cout << "constructor D " << endl; 38 } 39 40 ~D(){ 41 cout << "destrcutor D" << endl; 42 } 43 }; 44 45 int main(void){ 46 47 48 D d; 49 50 }
class B 默认构造函数抛出异常,而class C 默认构造函数是成功的,但并不会调用C的析构函数,由编译器回收
注释第7行的throw 0后则是下面结果:
第4:智能指针auto_ptr<T>, shared_ptr<T>, T类型构造函数异常,则
标签:
原文地址:http://www.cnblogs.com/geeker/p/4393319.html