Andreas DM
Andreas DM

Reputation: 11018

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

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
}

Upvotes: 9

Views: 1711

Answers (1)

syntagma
syntagma

Reputation: 24344

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

Upvotes: 14

Related Questions