Turns out that g++ compiler (used in Qt Creator by default) gives a mere warning if you don't have return statement in the non-void function, i.e.:
int* create_array(int n)
{
int* a = new int[n];
}
compiles fine.
This behavior is subj开发者_JAVA技巧ect to countless bug reports on g++ itself, but looks like developers consider this behavior conforming to C++ standard (which is debatable, cause it's a bit confusing in this part) as stated at 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.
However, the very same paragraph begins with:
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).
So aside from these (un)holy wars over the standard interpretation are there any options to make Qt flag this as an error at compile time?
This is not related to Qt but to g++.
In the build options, simply add the flag -Werror
and g++ will consider any warning as error. You may also need to use flag -Wall
to make g++ generate additional warnings, as it doesn't generate warnings for missing return statements (and many other situations) by default. There's no way to tune this setting on a per-warning basis however, so it's either everything or nothing.
You can use -Werror=warning_name
syntax to treat a specific warning as an error. For your case you can use -Werror=return-type
(where return-type
is the name of the "control reaches end of non-void function" warning). According to https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html.
精彩评论