[英]Why can I use ostream cout in a lambda although it wasn't captured?
This lambda fails because I haven't captured the variable: 这个lambda失败了因为我没有捕获变量:
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? 但是为什么ostream cout工作虽然它没有被捕获?
int main()
{
auto lambda = []{ cout << endl; }; // works
}
This is because std::cout
is defined in the following way (in the <iostream>
header): 这是因为
std::cout
是按以下方式定义的(在<iostream>
头文件中):
#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 (ie in the scope of the function/class). 而你的
val
变量是在本地定义的(即在函数/类的范围内)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.