This lambda fails because I haven't captured the variable:
int main()
{
int val = 5;
auto lambda = []{ return val; }; // error: val wasn't captured.
lambda();
}
But why does ostream cout work although it wasn't captured?
int main()
{
auto lambda = []{ cout << endl; }; // works
}
This is because std::cout
is defined in the following way (in the <iostream>
header):
#include <ios>
#include <streambuf>
#include <istream>
#include <ostream>
namespace std {
extern istream cin;
extern ostream cout;
extern ostream cerr;
extern ostream clog;
extern wistream wcin;
extern wostream wcout;
extern wostream wcerr;
extern wostream wclog;
}
while your val
variable is defined locally (i.e. in the scope of the function/class).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With