Unexpected gcc warning: function returns address of local variable - is it a compiler bug?

会有一股神秘感。 提交于 2021-01-28 05:20:52

问题


Following is the minimum working example (ok, in fact it's minimum non-working example :-)). When compiled with gcc (from version 5.0 up to 9.3) it fires the following warning. It even seems to fire the warning only in release build (-02 and higher).

Code:

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;
}

Compiler Output:

<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

The code above compiles ok with both MSVC and clang and it even compiles fine with gcc 10.1. It also compiles ok in debug (with -O1 or -O0) with older gcc versions.

Can you see anything incorrect in the code, or is it really a compiler issue?

Observation

When I add a deleted copy constructor to class A (A(const A&) = delete;), the warning disappears and the compiler stops to create a local variable.

Try You can try on gcc.godbolt.org

来源:https://stackoverflow.com/questions/62328409/unexpected-gcc-warning-function-returns-address-of-local-variable-is-it-a-com

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