Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does Q_REQUIRED_RESULT do?

Tags:

c++

qt

qt4

I was just reading Qt4-source code and found the precompiler define Q_REQUIRED_RESULT multiple times in qstring.h (and in other locations).

What does it actually do and why is it nowhere documented (would fit here)?

It is defined as follows:

#ifndef Q_REQUIRED_RESULT
#  if defined(Q_CC_GNU) && !defined(Q_CC_INTEL) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 1))
#    define Q_REQUIRED_RESULT __attribute__ ((warn_unused_result))
#  else
#    define Q_REQUIRED_RESULT
#  endif
#endif
like image 412
feedc0de Avatar asked Feb 14 '17 12:02

feedc0de


1 Answers

It makes the compiler generate warnings if you don't use the return value of the function, because it's likely you're making a mistake. E.g.:

QString str("hello, world!");
str.toUpper();

// str is still lower case, the upper case version has been
// *returned* from toUpper() and lost. the compiler should warn about this!

In C++17, this has been standardized under the [[nodiscard]] attribute. It's not documented because it's not public API -- i.e. use it at your risk in your code, Qt can change it anytime. (OK, extremely unlikely, but still a possibility).

like image 155
peppe Avatar answered Nov 18 '22 00:11

peppe