c++ - Lambda 捕获 C++14

标签 c++ lambda c++14

我遇到过这样的符号:

int x = 4;
auto y = [&r = x, x = x+1]()->int { 
    r += 2;
    return x+2;
}();

你能解释一下这个说法吗?我是 C++03 的用户,最近升级到 C++11。从今天开始,我开始使用 C++14 并遇到了这个片段。

谢谢!

最佳答案

感谢@chris wikipedia reference .我发现的是 -

Here is nice explanation who don't know about the old lambda Captures of C++11

在 C++14 中:


C++11 lambda functions capture variables declared in their outer scope by value-copy or by reference. This means that value members of a lambda cannot be move-only types. C++14 allows captured members to be initialized with arbitrary expressions. This allows both capture by value-move and declaring arbitrary members of the lambda, without having a correspondingly named variable in an outer scope.

This is done via the use of an initializer expression:

auto lambda = [value = 1] {return value;};

The lambda function lambda will return 1, which is what value was initialized with. The declared capture deduces the type from the initializer expression as if by auto.

This can be used to capture by move, via the use of the standard std::move function:

std::unique_ptr<int> ptr(new int(10));
auto lambda = [value = std::move(ptr)] {return *value;};

因此上面的表达式将 x 更新为 6,并将 y 初始化为 7。

关于c++ - Lambda 捕获 C++14,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50020830/

相关文章:

C++ 作业 - 计算字数

c++ - Lambda 引用自身

c++ - 按类型访问具有重复类型的 std::tuple 应该会产生编译错误

c++ - 从用户代码注入(inject)默认模板参数类型

c++ - 更正 __bridge 与 ARC 和 C++ 互操作的用法? (如何避免内存泄漏?)

c++ - 从 std::async 返回的 std::future 在超出范围时挂起

c++ - 有没有办法检查一个字符串是否包含 C++ 中的 unicode 字符

c++ - 将 boost phoenix lambda 与 io_service 一起使用

python - python中单行lambda函数中的条件语句?

c++ - 如何使用类模板特化避免代码重复