Qt不是异常安全。这如何影响C ++代码? [英] Qt is not exception safe. How does this impact C++ code?

查看:141
本文介绍了Qt不是异常安全。这如何影响C ++代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Qt是目前不是例外安全,似乎也是它有可能。在与Qt交互的C ++代码上有什么限制?

Qt is not currently exception safe nor, it seems, is it ever likely to be. What restrictions does this place on C++ code which interacts with Qt?

如果我想使用Qt,我需要避免代码中的所有C ++异常吗?

Do I need to avoid all C++ exceptions in my code if I want to use Qt?

推荐答案

您可以对要在应用程序中使用的任何其他非异常安全库执行相同的两项操作:隔离在异常安全包装器中,或放弃异常并适应其风格。你真正要问的是第一个是否可行。

You can do the same two things you do with any other non-exception-safe library that you want to use in an application: Isolate it in exception-safe wrappers, or give up exceptions and adapt to its style. What you're really asking is whether the first is feasible.

对于你的文字问题,你绝对不需要避免所有的异常。所有返回错误代码的Qt函数,不能正常清理的类等等都可以很容易地被打包。你没有很好的理由在Qt抛出异常,所以没关系,你不能。并且你不经常将Qt对象传递到依赖于异常的非Qt库。等等。最棘手的是它想到如何编写,例如,一个 QImage 包装器,如果真正的构造函数成功与无效的值,这将破坏和抛出,这不是很难。

For your literal question, you definitely don't need to avoid all exceptions. All of the Qt functions that return error codes, classes that don't clean themselves up properly, etc. can be wrapped up pretty easily. And you have no good reason to throw exceptions at Qt, so it doesn't matter that you can't. And you don't often pass Qt objects to non-Qt libraries that depend on exceptions. And so on. The trickiest it gets it thinking about how to write, e.g., a QImage wrapper that will destroy and throw if the real constructor succeeds with an invalid value, and that's not very hard.

但是最大的问题是你不能通过信号槽连接抛出异常。如果你想以典型的方式组织你的代码,其中低级函数抛出大多数异常和顶级函数做大多数异常处理,但你想使用Qt作为大多数中间层,这可能不是将是令人愉快的*对于说,传统的重控制器MVC设计,其中大多数控制器是建立在Qt,你使用异常将最终是非常局部的,不是所有的帮助。另一方面,使用MVA设计或智能模型设计,你的大多数逻辑可能不是直接处理Qt,所以你仍然可以在相当大的边界外的异常。 (当然假设你不必使用Qt,而不必使用Qt。)

But the big issue is that you can't throw exceptions through signal-slot connections. If you wanted to organize your code in the typical way, where low-level functions throw most of the exceptions and top-level functions do most of the exception handling, but you want to use Qt as most of your middle layer, that's probably not going to be pleasant.* For, say, a traditional heavy-controller MVC design, where most of the controller is built on Qt, your use of exceptions is going to end up being very local and not be all that helpful. On the other hand, with a MVA design or a smart-model design, most of your logic may not be dealing with Qt directly at all, so you can still go wild with exceptions within pretty large boundaries. (Of course that assumes you don't use Qt where you don't have to.)

*即使在这里, >包装。例如,你不能跨越线程连接,条件等待,但你可以构建未来和执行器,以一种干净的方式在线程之间传递异常。使用同一种脚手架,您可以通过插槽传递异常。但是这是相当繁重的脚手架,你会得到一个非常不同的API比典型的Qt程序,所以它似乎不值得。

这篇关于Qt不是异常安全。这如何影响C ++代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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