What does lambda constant mean?

#include <iostream>
int foo(int i)
{
    const auto a = [&i](){ i = 7; return i * i; };
    a();
    return i;
}
int main()
{
    std::cout << foo(42) << std::endl;
    return 0;
}

Compiles ( g++ -std=c++11 -Wall -Wextra -Wpedantic main.cpp) and returns 7. Which is surprising for me, because, declaring it a apermanent object, I expected it to ibe called as const int&. This is clearly not the case, why?

+4
source share
6 answers

Lambdas as non-lambdas, except that implementation details are hidden. Therefore, it can be easier to explain using a non-lambda functor:

#include <iostream>
int foo(int i)
{
    struct F {
      int &i;
      int operator()() const { i = 7; return i * i; }
    };
    const F a {i};
    a();
    return i;
}
int main()
{
    std::cout << foo(42) << std::endl;
    return 0;
}

F int & i. const F , i . i ( ).

+4

i, , .

, int&. .

2 :

const int i = 5;
auto b = [&i]() { i++; }; //error on i++

a const int&.

i , ++ 14

int i = 5;
auto b = [i = static_cast<const int&>(i)]() { i++; }; //error on i++

int& const int& . , .

+5
[&i](){ i = 7; return i * i; }

class Lambda
{
public:
    Lambda(int& arg_i) : i(arg_i) {}

    auto operator() () const { i = 7; return i * i;}
private:
    int& i;
};

, :

const Lambda a(i);
a();

const Lambda const int& i;, int& const i;, int& i;.

+5

, :

int foo(int i)
{
    const auto a = [&i](){ i = 7; return i * i; };
    a();
    return i;
}

-. const .

+2

, , i, a const i .

, , - i , , .

:

class A
{
public:
    A(int& y) : x(y) {} 
    void foo(int a) const { x = a; } // But it const?!
private:
    int& x;
};

int main()
{
    int e = 0;
    const A a(e);
    a.foo(99);
    std::cout << e << std::endl;
}

"99", foo a, e.
( , , .)

"const, " const .

, :

class A
{
public:
    A(int* y) : x(y) {} 
    void foo(int a) const { *x = a; } // Doesn't modify x, only *x (which isn't const).
private:
    int* x;
};
0

, const, - , : const auto a.

Therefore, you cannot change the value of your lambda expr link abecause it is const, but its parameter passed by reference &i, can be changed in the context of the lambda expression.

0
source

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


All Articles