【问题标题】:Warning returning a captured reference from a lambda警告从 lambda 返回捕获的引用
【发布时间】: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,我希望编译器警告未处理的情况。

标签: c++ c++11 lambda


【解决方案1】:

这确实是 Clang 中的一个错误 - 您通过引用正确地捕获了这两个变量,并且没有创建悬空引用。我假设每次有人返回对任何东西(无论是 lambda 还是函数)中的堆栈变量的引用时,Clang 都会自动发出警告。

Clang 3.5 does not show this warning anymore, neither does GCC 4.9.0.

【讨论】:

  • 而且 gcc 4.7.1 没有警告。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-23
  • 1970-01-01
  • 2017-02-23
  • 2020-04-20
  • 2018-05-02
  • 2011-01-07
相关资源
最近更新 更多