Search code examples
c++qtqt4

What does Q_REQUIRED_RESULT do?


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

Solution

  • 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).