Warning on returning taken link from lambda

I tried using lambda to conditionally link a reference to one of two variables:

int foo, bar;
int &choice = [&]() -> int & {
    if (true /* some condition */) {
        return foo;
    } else {
        return bar;
    }
}();

This gives a warning in clang 3.4:

stack_stuffing.cpp:5:20: warning: reference to stack memory associated with
      local variable 'foo' returned [-Wreturn-stack-address]
            return foo;
                   ^~~
stack_stuffing.cpp:7:20: warning: reference to stack memory associated with
      local variable 'bar' returned [-Wreturn-stack-address]
            return bar;
                   ^~~

But I only return links to the memory stack, which are in the area where the lambda is called. Is this behavior indicated, unspecified, or a clang error?

+4
source share
1 answer

This is really a mistake in Clang - you correctly capture both variables by reference and do not create any dangling links. I assume that Clang automatically issued a warning every time someone returned a link to a stack variable in everything, be it a lambda or a function.

Clang 3.5 , GCC 4.9 0,0.

+4

All Articles