c++ - 意外的 gcc 警告:函数返回局部变量的地址 - 是编译器错误吗?
问题描述
以下是最小的工作示例(好吧,实际上它是最小的非工作示例:-))。当使用 gcc(从 5.0 到 9.3)编译时,它会触发以下警告。它甚至似乎只在发布版本(-02
和更高版本)中触发警告。
代码:
class A
{
};
class B
{
const A& getA() const
{
static A a;
return a;
}
const A& get(bool b) const;
};
const A& B::get(bool b) const
{
return static_cast<const A&>(b ? getA() : getA());
}
int main(int argc, char** argv)
{
return 0;
}
编译器输出:
<source>: In member function 'const A& B::get(bool) const':
<source>:17:50: warning: function returns address of local variable [-Wreturn-local-addr]
return static_cast<const A&>(b ? getA() : getA());
<source>:17:50: note: declared here
return static_cast<const A&>(b ? getA() : getA());
Compiler returned: 0
上面的代码可以使用 MSVC 和 clang 编译,甚至可以使用 gcc 10.1 编译。它还可以在使用旧 gcc 版本的调试(使用-O1
or )中编译。-O0
你能在代码中看到任何不正确的地方,还是真的是编译器问题?
观察
当我将已删除的复制构造函数添加到类 A ( A(const A&) = delete;
) 时,警告消失并且编译器停止创建局部变量。
试试 你可以在gcc.godbolt.org上试试
解决方案
推荐阅读
- jquery - 如何使用 jquery 库显示 .json 文件中的内容?
- django - 尝试迁移时完整性错误不是空约束失败
- java - Java URL:获取 URL 对象的根(删除路径)
- ios - Xamarin iOS 中的 Swift 框架 - NSUnknownKeyException 原因:[
setValue:forUndefinedKey:] - r - 查找和替换完全匹配的部分字符串 (gsub)
- android - 使用 Android NDK 的此目标不支持 Crypto++ 和 neon_vector_type 属性?
- reactjs - 如何根据 URL 设置 React.useState
- r - 用 probplot 叠加两个概率图
- typescript - 通过泛型在 TypeScript 中将元组转换为对象
- python - 如何在 Python 中使用 Selenium 单击按钮?