std::cout
is an instance of std::ostream
. I can see the declaration of std::cout
in a file named /usr/include/c++/7/iostream
:
extern ostream cout; /// Linked to standard output
And std::ostream
is defined by typedef std::basic_ostream<char> std::ostream
.
What's more, it seems that you can't create an instance of std::ostream
. See this demo code snippet:
#include<iostream>
int main()
{
std::ostream os;
return 0;
}
Here is what the compiler complains about the code snippet above:
In file included from /opt/compiler-explorer/gcc-4.9.0/include/c++/4.9.0/iostream:39:0,
from <source>:1:
/opt/compiler-explorer/gcc-4.9.0/include/c++/4.9.0/ostream: In function 'int main()':
/opt/compiler-explorer/gcc-4.9.0/include/c++/4.9.0/ostream:384:7: error: 'std::basic_ostream<_CharT, _Traits>::basic_ostream() [with _CharT = char; _Traits = std::char_traits<char>]' is protected
basic_ostream()
^
<source>:5:18: error: within this context
std::ostream os;
^
The question arises, since the std::basic_ostream<_CharT, _Traits>::basic_ostream()
is marked protected, how std::cout
is created?
This link on CppReference seems not very meaningful. It does not clearly tell me how std::cout
is implemented and how std::cout
is created by the constructor of std::ostream
. As far as I can see, the most related information is:
The global objects
std::cout
andstd::wcout
control output to a stream buffer of implementation-defined type (derived fromstd::streambuf
), associated with the standard C output streamstdout
.
And nothing more.
I am working on Ubuntu
with gcc 4.9
Thanks to @NathanPierson.
He told me that
std::basic_ostream
has a constructor that takes a pointer to astd::basic_streambuf
object.std::cout
is initialized using a pointer to an instance of some implementation-defined derived class ofstd::basic_streambuf
.
, which moves me closer to the answer.