2017-02-14 12 views
2

我刚刚读取Qt4源代码,发现预编译器在qstring.h(和其他位置)中多次定义了Q_REQUIRED_RESULTQ_REQUIRED_RESULT做什么?

它实际上做了什么为什么它没有记录(适合here)?

它的定义如下:

#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 

回答

4

它使编译器生成警告,如果你不使用函数的返回值,因为很可能你犯了一个错误。例如:

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! 

在C++ 17中,这已经标准化为[[nodiscard]] attribute。它没有被记录,因为它不是公共API--即在代码中使用它有风险,Qt可以随时更改它。 (好吧,不太可能,但仍有可能)。