继续上一篇文章提到的构造异常话题,下面继续谈另外两个场景,即多继承构造异常,以及智能指针构造异常

第3:对多继承当中,某个基类构造异常,而其他基类已构造成功,则构造成功的基类不会析构,由编译器负责回收

 class B{

 public:
B(){
age = ;
cout << "construct B default" << endl;
throw ;//抛出异常
} ~B(){
cout << "destructor B ,age=" << age << endl;
}
private:
int age;
}; class C{
public:
C(){
//得到指定范围[m,n]的随机数:r = rand()%(n - m + 1) + m;
int r = rand()%(-)+;
num = r;
cout << "constuctor C ,num = " << num << endl; }
~C(){
cout << "destructor C, num = " << num << endl;
}
private:
int num;
}; class D:public C, public B{ public:
D(){
cout << "constructor D " << endl;
} ~D(){
cout << "destrcutor D" << endl;
}
}; int main(void){ D d; }

class B 默认构造函数抛出异常,而class C 默认构造函数是成功的,但并不会调用C的析构函数,由编译器回收

注释第7行的throw 0后则是下面结果:

第4:智能指针, 使用stl容器存放shared_ptr<T> 对象,若T构造函数发生异常,则前面成功构造的对象由编译器负责回收,见代码

 class C{
public:
C(){
//得到指定范围[m,n]的随机数:r = rand()%(n - m + 1) + m;
int r = rand()%(-)+;
num = r;
cout << "constuctor C ,num = " << num << endl;
if(!(r % )){
throw r;//当随机数r为4的倍数时抛出异常
}
}
~C(){
cout << "destructor C, num = " << num << endl;
}
private:
int num;
}; int main(void){ typedef shared_ptr<C> spc;
vector <spc> vc;
for(auto i = ; i < ; i++){
vc.push_back( spc(new C()) );
}
}

结果如下:当C构造函数中num等于4直接throw 异常

若注释第9行的throw r,则vector中所有元素都构造成功,main函数结束,调用C析构函数

好了,大概就这几种情况,其他没有列举的场景,你不妨再试一下,我相信结果是一样的

结论:但构造函数发生异常,其之前成功构造的基类成员、类成员、初始化列表,stl存放的智能对象都由编译器负责回收,程序员无权过问,也不需过问。

以上所有代码都是在Ubuntu 14.04(64)测试,如果有问题,欢迎指出。

最新文章

  1. AngularJs之六(服务)
  2. Hbase Java API详解
  3. 在linux和windows下自动备份数据库
  4. ASP.NET fails to detect Internet Explorer 10
  5. Ubuntu下添加Eclipse快捷方式
  6. LogMiner学习笔记
  7. Jquery 遍历数组之$().each方法与$.each()方法介绍
  8. 【WPF】如何获取命令行参数
  9. os.path python使用遍历文件夹文件
  10. 图tp delDataById问题
  11. 第七章 函数表达式和函数声明,关于this对象 ,私有作用域(function(){})() ,私有变量和特权方法
  12. WebApi用户登录验证及服务器端用户状态存取
  13. 微信小程序image bindload事件失效不触发
  14. mysql数据库优化(转)
  15. python第一百一十七天-----ModelForm组件
  16. linux学习问题总结
  17. Python3之网络爬虫&lt;0&gt;初级
  18. vue子组件传参给父组件
  19. 使用C#和MSMQ开发消息处理程序
  20. noi2017 day1 题解

热门文章

  1. nginx的安装和负载均衡例子(RHEL/CentOS7.4)
  2. Yahoo! 35条网站性能优化建议
  3. tensorflow队列tf.FIFOQueue | enqueue | enqueue_many | dequeue | dequeue_many
  4. JAVA中的面向对象与内存解析_1
  5. SQL分支语句与循环语句
  6. Redis 系列(02)数据结构
  7. bash 中的特殊变量
  8. 【记录】vue构建项目npm install错误run `npm audit fix` to fix them, or `npm audit` for details
  9. thinkphp5 自动注册Hook机制钩子扩展
  10. 一、Nuget管理