Quantcast
Channel: Active questions tagged gcc - Stack Overflow
Viewing all articles
Browse latest Browse all 22072

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

$
0
0

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.

TryYou can try on gcc.godbolt.org


Viewing all articles
Browse latest Browse all 22072

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>