简体   繁体   English

为什么我可以在lambda中使用ostream cout虽然它没有被捕获?

[英]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.

相关问题 如何使用void printMatrix(ostream&os = cout)const? - How can I use void printMatrix( ostream& os = cout ) const? 如何创建一个新类以继承ostream并将其用作cout但带锁 - How can I create a new class to inherit ostream and use it as cout but with lock 为什么我不能更改由 lambda 函数中的副本捕获的变量的值? - Why can't I change the value of a variable captured by copy in a lambda function? 如何传递ostream并使用cout在函数中的屏幕上显示? - How do I pass a ostream and use cout to display on the screen in a function? 为什么我的 c++ lambda function 抓不到? - Why can't my c++ lambda function be captured? 为什么我不能重载ostream的&lt;&lt;运算符? - Why can't I overload ostream's << operator? 为什么我不能在+ operator的字符串中使用fixed和setprecision()而不是&lt; - Why can't I use fixed and setprecision() with +operator for strings instead of <<operator for cout 为什么不能将constexpr与lambda函数一起使用? - Why can't I use constexpr with lambda function? 为什么我不能在 constexpr lambda 函数中使用 std::tuple - Why can't I use a std::tuple in a constexpr lambda function 为什么我不能使用 lambda 作为类中定义的集合的比较器? - Why can't I use a lambda as a comparator for a set defined in a class?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM