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

This compiles( g++ -std=c++11 -Wall -Wextra -Wpedantic main.cpp ) and prints 7. Which is surprising to me, because by declaring a to be a constant object, I would have expected i to be referenced as const int&. It clearly isn't, why?

12
  • 5
    Which part of your code captures j by const ref? I don't understand the problem. You made a function to take i, ignore its value, make it 7, square it, then return the result (49) ... which is exactly what happened! All you're doing with j is briefly storing 49 in a named variable before returning it. Can you clarify your intention please. Commented Oct 14, 2016 at 11:37
  • 2
    Now you don't have a variable named j at all. All you're doing with this altered code is setting i to 7, returning 49 then discarding that 49 value. Commented Oct 14, 2016 at 11:38
  • Because you captured by non-const ref. That's just like asking why on can modify stuff though a int *const.
    – Baum mit Augen
    Commented Oct 14, 2016 at 11:39
  • I dont understand your question like @LightnessRacesinOrbit stated.
    – amanuel2
    Commented Oct 14, 2016 at 11:39
  • 1
    I'm a bit late to this party, but indeed this is a nice use case for C++ Insights: cppinsights.io/s/fe317135
    – andreee
    Commented Aug 27, 2020 at 9:29

6 Answers 6

21

Lambdas are just like non-lambdas, except their implementation details are hidden. Therefore, it may 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 has a int & reference member i. const F cannot have its instance data modified, but a modification to i isn't a modification to its instance data. A modification to its instance data would be re-binding i to another object (which isn't allowed anyway).

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

is mainly equivalent to

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

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

And so then you have:

const Lambda a(i);
a();

And the const Lambda won't promote its member to const int& i; but int& const i; which is equivalent to int& i;.

8

When you capure i it is captured as the type it is.

So internally it has a int&. A const before the variable declaration of the closure does not change anything for the lambda.

You have 2 options to solve this:

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

This way a const int& will be captured.

If you cannot change i for some reasons you can do this in c++14

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

This casts the int& to a const int& and will be stored as such in the lambda. Though this is way more verbose as you can see.

2
  • If he doesn't want to change i it might be better to take it by copy.
    – krzaq
    Commented Oct 14, 2016 at 11:53
  • @krzaq yeah but this would be useful for cases where you have bigger objects you don't want to copy. In case of int this is kind of not needed.
    – Hayt
    Commented Oct 14, 2016 at 11:53
2

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;
};
2

In the code you gave:

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

You are not assigning after you initialized your constant lambda function. Therefore, const doesn't mean much in this context.

6
  • I didn't, but your answer doesn't seem to make sense to me.
    – krzaq
    Commented Oct 14, 2016 at 11:48
  • @krzaq it states in my answer : The OP Initialized the constant lambda at first. And then he didn't assign that lambda a different value , there the const modifier doesn't play a big role here.. What don't you understand about that?
    – amanuel2
    Commented Oct 14, 2016 at 11:50
  • Me neither. @Vorac: Nothing... it means you wouldn't be able to alter a, or its members, but you're not trying to do that here anyway. Were you expecting it to magically change the internal int& to a const int&? – Lightness Races in Orbit 9 mins ago Your answer addresses the first point, while my struggle is with the second. I edited the question in an attempt to clear this up.
    – Vorac
    Commented Oct 14, 2016 at 11:50
  • @Vorac what dont you get.. please state.
    – amanuel2
    Commented Oct 14, 2016 at 11:51
  • 1
    I downvoted it because it doesn't say anything of value. Commented Oct 14, 2016 at 12:19
1

What you have declared as const it isn't the context of your anonymous function or lambda exspression and its parameters, but only the reference at that lambda expression: const auto a.

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

3
  • 2
    a is not a reference. Commented Oct 14, 2016 at 12:19
  • I haven't gone in language details level.. I thought that was sufficient give an abstract indication of the role of the variable assigned with lambda expression address, and that is: a "reference" to a lambda expression or an anonymous function... Commented Oct 14, 2016 at 13:30
  • 2
    It is not a reference. Commented Oct 14, 2016 at 13:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.