Lambda capture as const reference?

后端 未结 8 1693
春和景丽
春和景丽 2020-11-30 19:33

Is it possible to capture by const reference in a lambda expression?

I want the assignment marked below to fail, for example:

#include 

        
相关标签:
8条回答
  • 2020-11-30 20:17

    I think the capture part should not specify const, as the capture means, it only need a way to access the outer scope variable.

    The specifier is better specified in the outer scope.

    const string better_string = "XXX";
    [&better_string](string s) {
        better_string = s;    // error: read-only area.
    }
    

    lambda function is const(can't change value in its scope), so when you capture variable by value, the variable can not be changed, but the reference is not in the lambda scope.

    0 讨论(0)
  • 2020-11-30 20:21

    There is a shorter way.

    Note that there is no ampersand before "best_string".

    It will be of a "const std::reference_wrapper<< T >>" type.

    [best_string = cref(best_string)](const string& s)
    {
        best_string = s; // fails
    };
    

    http://coliru.stacked-crooked.com/a/0e54d6f9441e6867

    0 讨论(0)
提交回复
热议问题