Lambda Captures C++14

2020-02-10 06:00发布

I've encountered a notation like:

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

Can you explain this statement? I was a user of C++03 and recently upgraded to C++11. From today I starts C++14 and encountered this snippet.

Thanks!

标签: c++ lambda c++14
1条回答
够拽才男人
2楼-- · 2020-02-10 06:28

Thanks @chris for the wikipedia reference. What I found is -

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

In 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;};

So the above expression updates x to 6, and initializes y to 7.

查看更多
登录 后发表回答