No compiler warning for returning a reference to l

2019-07-20 11:06发布

问题:

Using:

g++ -Wall -ansi foo.cpp

I get the warning

foo.cpp:31: warning: reference to local variable ‘x’ returned

from the function :

int &bar(int x) {
     return x;
}

but, removing that function from the file, I get no warning from the following function:

int &get_max(int x, int y) {
    return x > y ? x : y;
}

Why does the compiler allow this?

回答1:

It looks like a bug, the warning is inconsistent, if we turn on optimization in gcc 5.1 it does catch this case:

warning: function may return address of local variable [-Wreturn-local-addr]
 return x > y ? x : y;
                    ^

while without optimization gcc misses it.

So the best thing to do would be to file a bug report. If they don't believe it is a bug or won't fix it then at least there will be a reference for others having the same issue.