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

问题描述

表示:一段代码据说如果代码中的运行时失败不会产生不良影响,例如内存泄漏,存储数据乱码或无效输出,则异常安全的代码即使发生异常,也必须满足代码上的不变量。



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



您在Qt中的最佳做法是什么来满足异常安全?您使用什么而不是异常处理?

解决方案

C ++具有非常强大的排除安全机制。由于异常,对所有超出范围的变量运行析构函数。这与Java之类的语言不同,其中异常安全要求程序员获得 catch 最终子句。 / 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的异常安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 08:50