Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Q_ASSERT instead of assert

Tags:

In Qt there is a Q_ASSERT macro. What's the advantage of using this instead of assert from <cassert> ?

like image 511
Zitrax Avatar asked Aug 08 '16 14:08

Zitrax


People also ask

What is Q_assert?

Q_ASSERT is a custom assert macro which supposedly enhances the standard assert function. The error message is handled by qFatal() , which can behave slightly better on some platforms than the standard assert macro.


2 Answers

Q_ASSERT is a custom assert macro which supposedly enhances the standard assert function.

The error message is handled by qFatal(), which can behave slightly better on some platforms than the standard assert macro. For example on Windows it will trigger the Visual Studio debugger at the point where the assertion fails instead of just calling abort().

You can also redirect the output of Qt error message functions such as qFatalto your custom message handler ( with qInstallMessageHandler() ). It can be useful for example if you want to redirect the errors message to a file.

Also note that Q_ASSERT is disabled with the macro QT_NO_DEBUG(while assert is disabled by NDEBUG) : this can be used to separate your asserts between Qt-related code and the rest.

like image 165
Louen Avatar answered Sep 28 '22 05:09

Louen


From the very same document:

It does nothing if QT_NO_DEBUG was defined during compilation.

So, think about it: Q_ASSERT is not contingent on the absence of NDEBUG, as assert is. #ifndef NDEBUG is required for assert() to do anything and also is often used to demarcate other general debug-only things in user (and possibly library..?) code.

Using a separate macro is a benefit for those who would want to debug only Qt-related things, without leaving NDEBUG undefined and thus weighing down the rest of the code with debug-only stuff that'll bloat the program if NDEBUG is not defined, particularly assert()s.

So, you could compile with -DNDEBUG but not -DQT_NO_DEBUG if you wanted to compile 'normal' things with release-mode semantics but still apply debugging to Qt stuff.

That's surely very useful when developing a complex GUI application. I don't use Qt (yet?) but see the benefit of using such things in my chosen toolkits of GTK+/gtkmm [ ...which I'm sure exist, but I haven't yet looked them up ;-) ]

I recall a recent animated discussion on this here, interwoven with discussion of an orthogonal proposal: ISO C++ Standard - Future Proposals › Exception stack trace information.

like image 24
underscore_d Avatar answered Sep 28 '22 04:09

underscore_d