Exception Safety in Qt

2020-02-25 04:53发布

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?

4条回答
\"骚年 ilove
2楼-- · 2020-02-25 05:29

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.

查看更多
走好不送
3楼-- · 2020-02-25 05:39

Qt is (mostly) not exception safe: http://doc.qt.io/archives/4.6/exceptionsafety.html

On the other hand dealing with exceptions correctly in event driven programming is very hard, so best is to avoid them when using Qt and pass error codes.

查看更多
Summer. ? 凉城
4楼-- · 2020-02-25 05:48

Qt classes are exception neutral as stated in the documentation.

You should stick with boolean values for handling error conditions, just like Qt itself.

Not using exceptions internally was done for portability reasons, because Qt has to support many different platforms (portability and exceptions don't mix that well).

Again, from the docs:

Currently, the only supported use case for recovering from exceptions thrown within Qt (for example due to out of memory) is to exit the event loop and do some cleanup before exiting the application. Typical use case:

QApplication app(argc, argv);
 ...
 try {
     app.exec();
 } catch (const std::bad_alloc &) {
     // clean up here, e.g. save the session
     // and close all config files.

     return 0; // exit the application
 }
查看更多
萌系小妹纸
5楼-- · 2020-02-25 05:50

My best practice is to not use (or at least avoid them as much as possible) C++ exceptions in Qt based code, which makes handling them a non-problem. Qt isn't really the reason for this though, I simply feel exceptions often make things unnecessarily more complicated than they should be. But it helps Qt itself is mostly exception troubles free... :)

查看更多
登录 后发表回答