【发布时间】:2014-11-04 20:36:53
【问题描述】:
我尝试使用 lambda 有条件地将引用绑定到两个变量之一:
int foo, bar;
int &choice = [&]() -> int & {
if (true /* some condition */) {
return foo;
} else {
return bar;
}
}();
这会在 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 范围内的堆栈内存的引用。此行为是指定的、未指定的还是 clang 错误?
【问题讨论】:
-
有什么特别的理由不使用
int& choice = some_condition? foo: bar?不过,我认为编译器不应该发出警告。 -
@DietmarKühl 枚举上的实际代码
switches,我希望编译器警告未处理的情况。