c++ - lambda 捕获变量的规则

标签 c++ visual-c++ lambda c++11 g++

例如:

class Example
{
public:
    explicit Example(int n) : num(n) {}
    void addAndPrint(vector<int>& v) const
    {
        for_each(v.begin(), v.end(), [num](int n) { cout << num + n << " "; });
    }
private:
    int num;
};

int main()
{
    vector<int> v = { 0, 1, 2, 3, 4 };

    Example ex(1);
    ex.addAndPrint(v);
    return 0;
}

当您在 MSVC2010 中编译并运行它时,您会收到以下错误:

错误 C3480:“Example::num”:lambda 捕获变量必须来自封闭函数作用域

但是,对于 g++ 4.6.2(预发布版),您将获得:

1 2 3 4 5

根据标准草案,哪个编译器是正确的?

最佳答案

5.1.2/9:

The reaching scope of a local lambda expression is the set of enclosing scopes up to and including the innermost enclosing function and its parameters.

和 5.1.2/10:

The identifiers in a capture-list are looked up using the usual rules for unqualified name lookup (3.4.1); each such lookup shall find a variable with automatic storage duration declared in the reaching scope of the local lambda expression.

由于num既没有声明在任何函数范围内,也没有自动存储期限,因此无法捕获。因此 VS 是对的,g++ 是错的。

关于c++ - lambda 捕获变量的规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7214623/

相关文章:

c++ - 将互斥保护构建到 C++ 类中的线程安全方法?

winapi - 使用 Win32 API 创建表

C++11;非静态数据成员初始化可以访问其他数据成员吗?

c# - 与泛型一起使用时,Expression.Convert(..., someGenericType) 会抛出 ArgumentException

c# - 替换表达式树中的类型

c++ - 预编译头对mfc有多大影响?

c++ - 链接到库需要 MFC80U.LIB

c++ - 如何在庞大的代码库中找到悬空的命名空间或预处理器指令

c++ - MFC 单文档应用程序用户输入

c++ - 谷歌模拟 : Mocked overloaded functions create warning C4373