2014-11-04 31 views
4

返回一个捕获的参考我试图使用lambda有条件地结合两个变量中的一个的引用:警告从拉姆达

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

这产生一个警告在铛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被调用的范围。这种行为是指定的,未指定的,还是一个铿锵声bug?

+0

有什么特别的理由不使用'int&choice = some_condition? foo:bar'?不过,我认为编译器不应该警告。 – 2014-11-04 20:57:32

+0

@DietmarKühl实际的代码'开关'在一个枚举上,我希望编译器警告未处理的情况。 – s4y 2014-11-04 21:16:19

回答

4

这确实是Clang中的一个错误 - 您通过引用正确捕获了这两个变量,并且没有创建任何悬空引用。我认为每当有人返回任何内容的栈变量引用时,Clang就会自动发出警告,不管它是lambda还是函数。

Clang 3.5 does not show this warning anymoreneither does GCC 4.9.0

+0

而海湾合作委员会4.7.1不警告。 – Surt 2014-11-04 20:55:44