Lambda Captures C++14

后端 未结 2 1426
被撕碎了的回忆
被撕碎了的回忆 2020-12-16 02:39

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

2条回答
  •  攒了一身酷
    2020-12-16 03:13

    This example is part of C++14 feature "Lambda capture Initializers", This allows creating lambda captures initialized with arbitrary expressions. Using this reference-captures can have different names than the referenced variable.

    If you run your code :

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

提交回复
热议问题