没有返回对局部变量的引用的编译器警告 [英] No compiler warning for returning a reference to local variable

查看:342
本文介绍了没有返回对局部变量的引用的编译器警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用:

g++ -Wall -ansi foo.cpp

我收到警告


foo.cpp:31:warning:引用局部变量'x'返回

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

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?

推荐答案

它看起来像一个错误,警告是不一致的,如果我们打开优化 gcc 5.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;
                    ^

而不进行优化 gcc错过了

因此,最好的办法是提交错误报告。如果他们不相信这是一个错误或不会修复,那么至少会有其他人有同样问题的参考。

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.

这篇关于没有返回对局部变量的引用的编译器警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆