Q_REQUIRED_RESULT 是做什么的?
What does Q_REQUIRED_RESULT do?
我刚刚阅读 Qt4 源代码,发现预编译器在 qstring.h(以及其他位置)中多次定义 Q_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
如果您不使用函数的 return 值,它会使编译器生成警告,因为您很可能会犯错误。例如:
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 下标准化。它没有记录,因为它不是 public API——也就是说,在你的代码中使用它需要你承担风险,Qt 可以随时更改它。 (好吧,极不可能,但仍有可能)。
我刚刚阅读 Qt4 源代码,发现预编译器在 qstring.h(以及其他位置)中多次定义 Q_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
如果您不使用函数的 return 值,它会使编译器生成警告,因为您很可能会犯错误。例如:
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 下标准化。它没有记录,因为它不是 public API——也就是说,在你的代码中使用它需要你承担风险,Qt 可以随时更改它。 (好吧,极不可能,但仍有可能)。