Lambda capture by value and the keyword "mutable"

The need for a keyword mutablein lambdas is a source of great confusion.

Consider the code:

int x = 10;

function<void()> lambda = [=]() mutable {x++; cout << "Inside lambda: x = " << x << "\n";};

cout << "Before lambda: x = " << x << "\n";
lambda();
cout << "After  lambda: x = " << x << "\n\n";

Conclusion:

Before lambda: x = 10
Inside lambda: x = 11
After  lambda: x = 10

As we can see, the variable xremains unchanged after lambda, so there are no side effects.

However, if we β€œforget” the variable keyword , we get an error.

Being an argument passing the default value in C ++, it makes no sense for me to use a mutable keyword.

Can someone write (even in pseudo-code) a class generated by the compiler instead of lambda?

thank

+4
source share
3 answers

mutable , , -, , .

- ( ) , , ?

, -, . , , :

struct Lambda {
    void operator()() { x++; }
    int x{10};
};

mutable, const:

struct Lambda {
    void operator()() const { x++; }
    int x{10};
};

x (10) , , , , .
, , :

auto lambda_x = x;

. .

+4
class Lambda
{
public:
   Lambda(const Lambda&);
   ~Lambda();

   // the main functor operator, const when lambda not mutable
   R operator()(Args args) const;

   // Only present for non-capture lambda         
   operator PlainCFunctionType () const; 

   // Only present for non-capture  lambda         
   PlainCFunctionType operator+() const;
private:
   // Gets called when lambda created, but you can't call it yourself
   Lambda(Captures captures...); 

   Captures captures;
};
+1

- , . , [=], const. mutable, . [&] .

+1
source

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


All Articles