https://gcc.gnu.org/bugzilla/show_bug.cgi?id=64329

Michael Stahl <mstahl at redhat dot com> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
                 CC|                            |mstahl at redhat dot com

--- Comment #1 from Michael Stahl <mstahl at redhat dot com> ---
i believe i've hit the same problem, here's the footgun reproducer i came up
with:



#include <functional>
#include <cstdio>

int foo = 42;

int const& bar()
{   
    return foo;
}

int main()
{   
    std::function<int const& ()> f{ [] () { return bar(); } };
    int const& rfoo = f();
    printf("%p %p\n", (void*)&foo, (void*)&rfoo);
    return &foo == &rfoo;
}


this is g++ (GCC) 5.3.1 20160406 (Red Hat 5.3.1-6)

> g++ -std=c++11 -Wall -Wextra -pedantic -Weffc++ -W lambdaref.cc  && ./a.out 
0x60204c (nil)


the problem is that the deduced return type of the lambda is a value
type, never a reference type.  this caught me by surprise, but it's
the same rule as for "auto".

if the C++ committee has to make surprising and error-prone type
inference rules, then at least implementations like g++ could
give a warning about returning a reference from a lambda that
is implicitly copied to a value, only to be implicitly converted
again into nothing.

Visual Studio 2013 gives a "warning C4172 returning address of local
variable or temporary" from somewhere inside its std::function code.

Reply via email to