编写C ++没有异常? [英] Writing C++ without exceptions?

查看:129
本文介绍了编写C ++没有异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此回答提到了两种处理异常安全的C ++库(例如Qt)的方法:

This answer mentions two ways to handle a C++ library (such as Qt) which is not exception safe:


  1. 在异常安全包装中隔离

  2. 放弃异常并适应其风格

答案详细介绍了第一个选项,但第二个选项的后果是什么:放弃例外?

The answer goes into detail about the first option, but what are the consequences of the second option: giving up exceptions?

在编写C ++时没有例外,语言的使用是如何限制的?例如,有标准库的部分是不安全使用吗?

When writing C++ without exceptions, how is the use of the language restricted? For example, are there parts of the standard library which are not safe to use?

(特别是,我假设在std :: bad_alloc的情况下,没有选择,但我的程序退出?)

(In particular, I assume that in the case of std::bad_alloc, I would have no choice but for my program to exit?)

推荐答案

事实上,我认为结果< T> 样式(也称为 expected< T> >,但我的灵感来自 Rust的版本,特别是< a href =http://doc.rust-lang.org/std/macro.try!.html =nofollow> try!宏,除了我不模板我的 Err 变体(对于失败的函数,所有错误是相同的)是很多更容易比使用异常。

It's not hard. In fact I argue that the Result<T> style (also known as expected<T> in Andrei's talk, but I was inspired by Rust's version, particularly the try! macro, except that I don't template my Err variant (for functions that fail, all errors are the same)) is a lot easier than using exceptions.

你真正要放弃的一件事是构造函数,可能会失败。

The one thing you really have to give up is constructors that do something that can possibly fail. Instead, use the named constructor idiom and only use pretty-much-aggregate constructors after you've already done.

至于 bad_alloc

As far as bad_alloc, just let it kill the process by unwinding.

这篇关于编写C ++没有异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆