C ++ 14 increment value inside lambda function using pointer-pointer

My task is to write a lambda function that increments the value, but I need to use value-0 capture-specifier. I am thinking of the following function:

auto lambda = [value = 0]{return ++value}

When this function is called, it must increment each time. But I know that this implementation is incorrect because it passed by value. How can I do this in C ++ 14?

+4
source share
2 answers

You need to make lambda mutable:

auto lambda = [value = 0]() mutable {return ++value;};
+12
source

You do not need a capture:

[]{ static int i=0; return ++i; }

Anything you need.

+1
source

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


All Articles