walfud

 

// parameterInLambda.cc
//

#include <iostream>
using namespace std;

int main()
{
    int x = 1234;
    function<int ()> byValue = [x](){ return x; };
    function<int ()> byReference = [&x](){ return x; };

    cout <<"x = 1234;" <<endl;
    cout <<"Before change, by Value: " <<byValue() <<endl;
    cout <<"Before change, by Reference: " <<byReference() <<endl;
    x = 4321;
    cout <<"x = 4321;" <<endl;
    cout <<"After change, by Value: " <<byValue() <<endl;
    cout <<"After change, by Reference: " <<byReference() <<endl;

    return 0;
}

  

 

  If you pass parameter by value, the value will decided at the point of lambda is defeined. Even you assign a new value to the variable after the lambda, the value in lambda will not care.

  If you pass parameter by reference, the value will decided at the point of lambda is used, just like pointer. In this case, if you assign a new value to the variable, lambda will dereference it and get the new value at each call.

分类:

技术点:

相关文章:

  • 2021-10-07
  • 2018-07-15
  • 2021-08-16
  • 2021-07-23
  • 2021-12-13
  • 2020-01-30
  • 2021-07-20
  • 2019-10-30
猜你喜欢
  • 2019-02-03
  • 2021-07-16
  • 2021-11-26
  • 2021-10-01
  • 2021-04-02
  • 2021-07-08
  • 2021-08-21
相关资源
相似解决方案