If I understand correctly, the question is why you're allowed to mutate i
even though a
is const
and presumably contains a reference to i
as a member.
The answer is that it's for the same reason that you're allowed to do this on any object - assigning to i
doesn't modify the lambda instance, it modifies an object it refers to.
Example:
class A
{
public:
A(int& y) : x(y) {}
void foo(int a) const { x = a; } // But it's const?!
private:
int& x;
};
int main()
{
int e = 0;
const A a(e);
a.foo(99);
std::cout << e << std::endl;
}
This compiles, and prints "99", because foo
isn't modifying a member of a
, it's modifying e
.
(This is slightly confusing, but it helps to think about which objects are being modified and disregard how they're named.)
This "const, but not really" nature of const
is a very common source of confusion and annoyance.
This is exactly how pointers behave, where it's more obviously not wrong:
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;
};
j
by const ref? I don't understand the problem. You made a function to takei
, ignore its value, make it 7, square it, then return the result (49) ... which is exactly what happened! All you're doing withj
is briefly storing 49 in a named variable before returning it. Can you clarify your intention please.j
at all. All you're doing with this altered code is settingi
to 7, returning 49 then discarding that 49 value.int *const
.