When studying the sample code for this question I had assumed it was Undefined Behaviour which was preventing subsequent uses of std::cout
from printing. But it
gcc ostream.tcc
line 319:
template<typename _CharT, typename _Traits>
basic_ostream<_CharT, _Traits>&
operator<<(basic_ostream<_CharT, _Traits>& __out, const char* __s)
{
if (!__s)
__out.setstate(ios_base::badbit);
gcc is simply performing a check that the standard does not guarantee, which is fine because it's undefined anyway.
basic_ostream
's operator<<(basic_ostream<>&, const char*)
function requires that the char*
is non-null - it is designed to print the string the pointer points to. So it is undefined behavior to send a null char*
to cout
. (See C++11 27.7.3.6.4/3 "Character inserter function templates").
However, basic_ostream
's operator<<(basic_ostream<>&, const void*)
function simply prints the value of the pointer, so a null pointer will work properly with that overload.