Reputation: 51685
I tried to use a lambda to conditionally bind a reference to one of two variables:
int foo, bar;
int &choice = [&]() -> int & {
if (true /* some condition */) {
return foo;
} else {
return bar;
}
}();
This yields 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 ever return references to stack memory that's in scope where the lambda is called. Is this behavior specified, unspecified, or a clang bug?
Upvotes: 4
Views: 387
Reputation: 60979
This is indeed a bug in Clang - you are correctly capturing both variables by reference and no dangling references are created. I presume Clang automatically issued a warning every time someone returned a reference to a stack variable inside anything, be it a lambda or a function.
Clang 3.5 does not show this warning anymore, neither does GCC 4.9.0.
Upvotes: 4