passByValue vs passByReference in lambda expression (C++0x)

 

// 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.

posted @ 2012-05-06 23:26  walfud  阅读(308)  评论(0编辑  收藏  举报