Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I use ostream cout in a lambda although it wasn't captured?

Tags:

c++

c++11

lambda

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
}
like image 979
Andreas DM Avatar asked May 04 '15 22:05

Andreas DM


1 Answers

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).

like image 132
syntagma Avatar answered Sep 22 '22 01:09

syntagma