No member function member error inside lambda expression?

This is a rather strange mistake for me. Check out the code below:

void test(void){ vector<string> v; v.push_back("hello"); auto fn=[=](){ v.push_back("world"); }; } 

The first push_back method passed the compilation, but the second failed, resulting in an error:

Error: there is no corresponding member function to call 'push_back'

Compiler Note:

** Note: (687, 36) the candidate function is not viable: the argument 'this' is of type 'const vector' (aka 'const vector, allocator →')

But the method is not marked const** .
Well, I do not use the const argument, and I cannot understand what the compiler is trying to tell me. Can anyone help me out?

+5
source share
3 answers

The default member functions of the Lambda call operator are const . If you want to work with a mutable call, say mutable :

 auto fn = [=]() mutable { // ^^^^^^^ v.push_back("world"); }; 

With the default const value, you should be explicit about the fact that you want to grab a copy of the vector and change that copy, not the original vector v .

In contrast, variables that are written by reference can be changed using constant member functions:

 auto fn = [&]() { // ^^^ v.push_back("world"); // modifies original "V"! }; 

(This is essentially because const T same as T , when T = U & , there are no "constant references" in C ++.)

+10
source

capture by value of const uses the mutable keyword (does not change the original vector):

 auto fn = [=]() mutable { v.push_back("world"); }; 

or by reference (changes the original vector):

 auto fn = [&]() { v.push_back("world"); }; 
+4
source

Because of the C++14 tag, and for completeness, I will also give a list of initializers as an alternative solution:

 [&vec = v](){ vec.push_back("world") }; 

If you want to write over a copy instead of a link:

 [vec = v]() mutable { vec.push_back("world") }; 

Initializer lists as a method of (say) capture are available with C++14 , as already mentioned.

0
source

Source: https://habr.com/ru/post/1247438/


All Articles