警告从Lambda返回捕获的引用 [英] Warning returning a captured reference from a lambda
问题描述
我尝试使用lambda有条件地将引用绑定到两个变量之一:
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;
}
}();
这会在clang 3.4中产生警告:
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;
^~~
但是我只返回对调用lambda范围内的堆栈内存的引用.此行为是指定的,未指定的还是叮叮当当的错误?
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?
推荐答案
这确实是Clang中的一个错误-您正确地通过引用捕获了两个变量,并且没有创建任何悬挂的引用.我认为Clang每次有人返回对内部变量(无论是lambda还是函数)的引用时,都会自动发出警告.
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 不再显示此警告,
Clang 3.5 does not show this warning anymore, neither does GCC 4.9.0.
这篇关于警告从Lambda返回捕获的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!