Q_REQUIRED_RESULT是什么意思?

7

我刚刚在阅读Qt4源代码时发现,在qstring.h(和其他位置)中多次出现了预编译器定义Q_REQUIRED_RESULT

它实际上是做什么的,为什么没有文档介绍(应该放在这里)?

它的定义如下:

#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
1个回答

11

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

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]]属性。它没有记录,因为它不是公共API - 也就是说,在您的代码中使用它要承担风险,Qt随时可能更改它。(好的,极其不太可能,但还是有可能的)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接