首页 > 解决方案 > 意外的 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 版本的调试(使用-O1or )中编译。-O0

你能在代码中看到任何不正确的地方,还是真的是编译器问题?

观察

当我将已删除的复制构造函数添加到类 A ( A(const A&) = delete;) 时,警告消失并且编译器停止创建局部变量。

试试 你可以在gcc.godbolt.org上试试

标签: c++gccgcc-warningcompiler-bug

解决方案


推荐阅读