Search code examples
c++lambdalocal-variablesreference-parameters

Is this reference to ostream a local variable


in c++primer 5th edition p393 it is written :

The variables captured by a lambda are local variables

The book then shows an ostream as a referenced parameter, captured by reference by the lambda. This is similar :

#include <iostream>
using namespace std;
void foo(ostream &os) {
    auto f = [&os]() { os << "Hellow World !" << endl; //return os;
    };
    f();
}
void main() {
    foo(cout);
    system("pause");
}

What i struggle with is that here os is not a local variable to foo, it exists outside of foo's scope, yet it can be captured by a lambda while "The variables captured by a lambda are local variables". What am i missing here? Also, why can the lambda not return os; ? After all, isn't os an object which exists outside of the lambda and foo's scope ?


Solution

  • What i struggle with is that here os is not a local variable to foo, it exists outside of foo's scope,

    No, it’s local, it does not exist outside of foo.

    The object that’s referenced by os exists outside of foo, because os is a reference. But that’s irrelevant here, since we’re talking about variables, not objects.

    Also, why can the lambda not return os;?

    It can, you just need to specify an explicit return type, otherwise the return type is inferred as std::ostream, i.e. the code will attempt to copy the stream, and it’s non-copyable.

    But the following works:

    auto f = [&os]() -> std::ostream& { return os << "Hellow World !" << endl; };