2017-02-14 10 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可以隨時更改它。 (好吧,不太可能,但仍有可能)。