我刚刚阅读 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
最佳答案
如果您不使用函数的返回值,它会使编译器生成警告,因为您很可能会犯错误。例如:
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 可以随时更改它。 (好吧,极不可能,但仍有可能)。
关于c++ - Q_REQUIRED_RESULT 做什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42225724/