Lambda capture as const reference?

后端 未结 8 1726
春和景丽
春和景丽 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.

提交回复
热议问题