c++ - Lambda:未评估上下文中未捕获的对象

标签 c++ lambda language-lawyer c++17

我希望指向标准段落,指出 following code格式良好:

int main() {
    int var = 0;
    return [] { return sizeof(var); }(); // var is not captured!
}

类似的例子出现,例如§ 8.4.5.2,但我找不到任何口头描述。

最佳答案

它是根据何时必须捕获实体来指定的,而不是根据何时不能捕获实体来指定。

[expr.prim.lambda.capture] (with some omissions)

8 ... If a lambda-expression or an instantiation of the function call operator template of a generic lambda odr-uses this or a variable with automatic storage duration from its reaching scope, that entity shall be captured by the lambda-expression. ...

[ Example:

void f1(int i) {
  int const N = 20;
  auto m1 = [=]{
    int const M = 30;
    auto m2 = [i]{
      int x[N][M];          // OK: N and M are not odr-used
      // ...
    };
  };
  // ...
}

— end example ]

代码示例中的关键是 var 未使用 odr,因为它是未计算的操作数。因此,不需要捕获它。

关于c++ - Lambda:未评估上下文中未捕获的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58264055/

相关文章:

c++ - 在 C++ 中将指向基类的指针传递给派生类的成员函数

c++ - 在 CMake 中可移植地设置编译器选项(如 -Wall 和 -pedantic)的最佳方法

c++ - 是否有关于诸如 erase/remove_if 之类的算法以及 remove_if 实现的可能副作用的编程标准?

c++ - 包含特定 boost header 时标准非 boost 文件中的错误

c# - lambda表达式问题

c# - 如何声明 Linq 表达式变量以便将其作为 dbParameter 处理

c# - 过滤两个数组以避免 Inf/NaN 值

compiler-errors - 为什么我不会在未使用的局部变量上出现编译器错误?

c++ - 通过依赖类型使用非类型模板参数的单类型模板参数类模板的部分特化

c++ - 变量不等同于 fstream 与声明