如何使Qt Creator在无返回语句上显示错误

How to make Qt Creator show error on no return statement

本文关键字:语句 显示 错误 返回 何使 Qt Creator      更新时间:2023-10-16

事实证明,g++编译器(默认情况下在Qt Creator中使用)给出一个简单的警告,如果你在非void函数中没有返回语句,即:

int* create_array(int n)
{
    int* a = new int[n];
}

运行良好。

此行为在c++本身中受到无数错误报告的影响,但看起来开发人员认为此行为符合c++标准(这是有争议的,因为在这一部分中它有点令人困惑),如http://gcc.gnu.org/bugzilla/show_bug.cgi?id=43943:

所述:
Flowing off the end of a function is equivalent to a return with no value; 
this results in undefined behavior in a value-returning function.

然而,同样的段落以:

  A return statement without an expression can be used only in functions 
  that do not return a value, that is, a function with the return type void,
  a constructor (12.1), or a destructor (12.4).

所以除了这些(un)神圣的战争在标准的解释有任何选项,使Qt标志这是一个错误在编译时?

这与Qt无关,而是与g++有关。

在构建选项中,只需添加标志-Werror, g++将把任何警告视为错误。您可能还需要使用标志-Wall来让g++生成额外的警告,因为默认情况下,它不会为丢失的返回语句(以及许多其他情况)生成警告。但是,没有办法在每次警告的基础上调整此设置,因此要么全部设置,要么不设置。

您可以使用-Werror=warning_name语法将特定警告视为错误。对于您的情况,您可以使用-Werror=return-type(其中return-type是"控制达到非无效函数结束"警告的名称)。根据https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html