异常安全在Qt [英] Exception Safety in Qt

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

问题描述

维基百科说,一段代码被认为是异常安全的,如果运行时失败在代码中不会产生不良影响,如内存泄漏,存储数据乱码或输出无效。异常安全代码必须满足不变量放置在代码上,即使发生异常。



似乎我们需要异常处理来处理异常安全。另一方面,异常处理在Qt应用程序中不是很流行,只要我看到。



您在Qt中的最佳实践是什么以满足异常安全?你使用什么来代替异常处理?

解决方案

C ++有一个非常强大的excpetion-安全机制。对于由于异常而超出范围的所有变量,将运行析构函数。这不同于Java之类的语言,其中异常安全需要程序员获得 catch finally 子句。 / p>

调用析构函数的C ++行为与堆栈上的Qt对象无缝地工作。 Qt类都有析构函数,无需手动清理。此外, QSharedPointer 可以用于管理堆分配的Qt对象;当最后一个指针超出范围时,对象被销毁。这包括指针由于异常而超出范围的情况。



因此,异常安全肯定存在于Qt中。它只是透明的。


Wikipedia says that "A piece of code is said to be exception-safe, if run-time failures within the code will not produce ill effects, such as memory leaks, garbled stored data, or invalid output. Exception-safe code must satisfy invariants placed on the code even if exceptions occur."

And it seems that we need exception handling for exception safety. Ot the other hand, exception handling is not very popular in Qt applications as long as I see.

What are your best practices in Qt to satisfy exception safety? What do you use instead of exception handling?

解决方案

C++ has a very powerful mechanism for excpetion-safety. Destructors are run for all variables that go out of scope due to an exception. This differs from languages like Java, where exception-safety requires the programmer to get the catch and finally clauses right.

The C++ behavior of calling destructors works seamlessly with Qt objects on the stack. Qt classes all have destructors and none require manual cleanup. Furthermore, QSharedPointer<T> can be used to manage heap-allocated Qt objects; when the last pointer goes out of scope the object is destroyed. This includes the case where the pointer goes out of scope due to an exception.

So, exception-safety is certainly present in Qt. It's just transparent.

这篇关于异常安全在Qt的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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