Spurious warning about returning reference to lambda capture

Hi all,

I'm seeing what I think is a spurious warning from this code:

#include <string>

int
main(int argc, char**)
{
  std::wstring x;
  auto f = [x] () -> const std::wstring& { return x; };

  return 0;
}

The warning is:

stack_local.cpp:7:50: warning: reference to stack memory associated with local variable 'x' returned [-Wreturn-stack-address]
         auto f = [x] () -> const std::wstring& { return x; };

I think since x is actually a lambda capture, not a local variable, it is okay to return its address (so long as the caller finishes with the address before the lambda is destroyed).

(In my particular use case the lambda lifetime is tied to the callers
lifetime.)

Is my analysis correct?

If so, should we suppress this warning for lambda captures?

Thanks,

Joseph

PS. This is from:

cw01:~ galb$ clang++ --version
Apple LLVM version 5.0 (clang-500.2.79) (based on LLVM 3.3svn)
Target: x86_64-apple-darwin13.0.0
Thread model: posix

Hi all,

I'm seeing what I think is a spurious warning from this code:

#include <string>

int
main(int argc, char**)
{
        std::wstring x;
        auto f = [x] () -> const std::wstring& { return x; };

        return 0;
}

The warning is:

stack_local.cpp:7:50: warning: reference to stack memory associated with
local variable 'x' returned [-Wreturn-stack-address]
        auto f = [x] () -> const std::wstring& { return x; };

I think since x is actually a lambda capture, not a local variable, it is
okay to return its address (so long as the caller finishes with the address
before the lambda is destroyed).

(In my particular use case the lambda lifetime is tied to the callers
lifetime.)

Is my analysis correct?

If so, should we suppress this warning for lambda captures?

Yes, and yes. This is llvm.org/PR17374. Patches welcome!