1
int main() {
    int x;
    auto& getx = [&]() {
        return x;
    }
    
    getx() = 1;
}

This doesn't seem possible, as it gives me:

error: cannot bind non-const lvalue reference of type 'main()::<lambda()>&' to an rvalue of type 'main()::<lambda()>'|

Why ? and how to do it

0

2 Answers 2

3

A lambda expression creates a temporary object (called a closure) of an unknown class type. Temporary objects can't be assigned to non-const references. That means you need

auto&& getx = [&]() {
    return x;
}

so that you get an rvalue reference to the closure, or

auto getx = [&]() {
    return x;
}

so you just get the closure.

That will get the code to compile, but still needs one more bit to make getx's return value to be a reference to x. To do that you need to add

auto getx = [&]() -> int& {
    return x;
}

// or

auto getx = [&]() -> auto& {
    return x;
}

// or

auto getx = [&]() -> decltype(auto) {
    return x;
};

Also note that main must always return an int. You should turn up your compiler warning level so that it errors out if you try and use void main.

Sign up to request clarification or add additional context in comments.

5 Comments

thx for the quick reply, however, what I asked for was a lvalue, and these two aren't
@Sho What go you want getx to be? Do you want it to be a reference to x, or do you want it to return a reference to x, or do you want to to return the value of x?
quoting the title "Lambda function returning lvalue from higher scope" basicly something that alows me this getx() = 1;
@Sho Okay, I've updated the answer to include that part as well.
nice answer as well, and in the end better constructed than the other one! The other helped me quicklier though, but yours explained it well
2

You have to specify that lambda returns reference to int - int&, and call closure by ():

auto& getx = [&]() -> int& { // -> int& added
    return x;
}();                         // () added

Temporary value cannot be bound to lvalue reference. If you want to make getx to be as a reference to x variable, you have to return reference from your lambda.

2 Comments

You can also use -> auto& to not specify the type
Really big thank you for that, it comes along very nicely with the rest of my code, and made me learn about closure 👍

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.