No compiler warning for returning a reference to local variable

走远了吗. 提交于 2019-12-24 04:17:34

问题


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.



来源:https://stackoverflow.com/questions/29872531/no-compiler-warning-for-returning-a-reference-to-local-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!