Possible Duplicate:
Implementing a no-op std::ostream
Is there any stream equivalent of NULL in c++? I want to write a function that takes in a stream if the user wants to have the internal outputted to somewhere, but if not, the output goes into some fake place
void data(std::stream & stream = fake_stream){
stream << "DATA" ;
}
i want to be able to chose to do data()
or data(std::cout)
Edit: Taken from @Johannes Schaub - litb's mail here with slight modifications:
Use those:
Now, this looks cool and all, but the following is way shorter and works, because if a null pointer is provided to the constructor of
ostream
, it automatically sets the badbit and silently ignores any writes:The standard guarantees this works, beginning from
27.6.2.2 [lib.ostream.cons] p1
which describes the constructor ofostream
that takes a pointer to astreambuf
:The relevant function from
basic_ios
,27.4.4.1 [lib.basic.ios.cons] p3
:The important row from Table 89:
What happens if the
badbit
is set is described under27.6.2.6 [lib.ostream.unformatted]
:This implies that, in case the
sentry
is false, it does not. Here is how thesentry
converts tobool
, taken from27.6.2.3 [lib.ostream::sentry] p3 & p5
:(
ok_
is a member ofostream::sentry
of typebool
.)Note that these quotes are still present in C++11, just in different places. In order of appearance in this answer:
27.6.2.2 [lib.ostream.cons] p1
=>27.7.3.2 [ostream.cons] p1
27.4.4.1 [lib.basic.ios.cons] p3
=>27.5.5.2 [basic.ios.cons]
27.6.2.6 [lib.ostream.unformatted]
=>27.7.3.7 [ostream.unformatted] p1
27.6.2.3 [lib.ostream::sentry] p3 & p5
=>27.7.3.4 [ostream::sentry] p4 & p5
Linux file /dev/null is a black hole like you're looking for. In Windows there's a device called NUL:. I've never tried to open that file, but I've used it from the command line
you can try ostream(NULL,false), the first input is target output and I don't know what the second input exaclty mean but after tracing code it seems just because ostream has no place to write to, calling
operator <<
is just ignored by ostream. I mean in the first call state changes to bad and after that it's always ignoring input data because of stream state ,so you can use the following code :