34

This does not compile since the lambda expression returns by value:

#include <iostream>

class Item
{
public:
    int& f(){return data_;}
private:
    int data_ = 0;
};

int main()
{
    Item item;
    auto lambda = [](Item& item){return item.f();};
    lambda(item) = 42;  // lambda(item) is a rvalue => compile time error 
    std::cout << item.f() << std::endl;
    return 0;
}

Is there a way around this? Can I force a lambda to return by reference?

2
  • 1
    Where did you learn about lambdas that only taught the shortened version? The full syntax includes not only a way to explicitly state the return type, but a place for mutable, exception specifications, attributes, and captures. I could see skipping over some of those when first teaching lambdas, but not the return type.
    – bames53
    Commented May 28, 2013 at 16:59
  • It was on wikipedia en.wikipedia.org/wiki/…. I stopped reading on "The return type is implicit". Turns out that the main article contains the full syntax though. Commented May 29, 2013 at 0:45

1 Answer 1

59

You should specify the lambda return type to be int&. If you leave the return type off [and the lambda is of form return expression; it will automatically deduce the return type.

#include <iostream>

class Item
{
public:
    int& f(){return data_;}
private:
    int data_ = 0;
};

int main()
{
    Item item;
    auto lambda = [](Item& item) ->int& {return item.f();}; // Specify lambda return type
    lambda(item) = 42;
    std::cout << item.f() << std::endl;
    return 0;
}
2
  • 29
    In C++14 it is also allowed to write auto& in trailing return type which will be more simple in case if type of return value is complex
    – Predelnik
    Commented Sep 10, 2015 at 8:54
  • or decltype(auto) Commented Jan 5, 2021 at 5:24

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.