Standard no-op output stream - c++

Is there a way to create an ostream instance which basically doesn't do anything ?
For example :
std::ostream dummyStream(...);
dummyStream << "Nothing will be printed";
I could just create an ostringstream, but data will be buffered (and I really don't want to make anything with them, so it adds a useless overhead).
Any idea ?
[edit] Found this related question which suits my needs. However, I think it could be useful to have a answer saying how to create a valid (no badbit) output stream with standard c++.

You need a custom streambuf.
class NullBuffer : public std::streambuf
{
public:
int overflow(int c) { return c; }
};
You can then use this buffer in any ostream class
NullBuffer null_buffer;
std::ostream null_stream(&null_buffer);
null_stream << "Nothing will be printed";
streambuf::overflow is the function called when the buffer has to output data to the actual destination of the stream. The NullBuffer class above does nothing when overflow is called so any stream using it will not produce any output.

If this is to disable logging output, your dummyStream would still cause arguments to be evaluated. If you want to minimize impact when logging is disabled, you can rely on a conditional, such as:
#define debugStream \
if (debug_disabled) {} \
else std::cerr
So if you have code like:
debugStream << "debugging output: " << foo() << std::endl;
No arguments will be evaluated if debug_disabled is true.

The basic method voor new stream classes is:
Derive a class from std::streambuf;
Override the virtual functions in that class. This is where the real work is done. In your case, empty implementations should be good enough.
Derive a class from std::ostream with one member, your streambuf class.
The constructor of your streamclass should forward the pointer to that member to the base constructor of std::ostream.
I'm afraid you won't get rid of the formatting step, though.
Hopefully this gives you some pointers; I don't have the time to expand this into a full answer, sorry.
Update: See john's answer for details.

For runtime-controllable redirection of log messages, a self-contained solution combining the ideas of john and Sjoerd:
class DebugStream {
private:
class NullStream : public std::ostream {
private:
class NullBuffer : public std::streambuf {
public:
int overflow(int c) override { return c; }
} buffer_;
public:
NullStream() : std::ostream(&buffer_) {}
} null_;
std::ostream &output_;
bool enabled_;
public:
DebugStream(std::ostream &output = std::cout) : output_(output), enabled_(false) {}
void enable(const bool enable) { enabled_ = enable; }
template <typename T> std::ostream& operator<<(const T &arg) {
if (enabled_) return output_ << arg;
else return null_ << arg;
}
};
extern DebugStream debug_stream;
#define TRACE_ENABLE(x) debug_stream.enable(x)
#define TRACELN(x) debug_stream << x << std::endl
#define TRACE(x) debug_stream << x
Then you can do stuff like:
TRACELN("The value of x is " << x " and the value of y is " << y);
It would also be easy to just remove the trace statements from a release version completely with #define the trace macros to empty statements.
You still need to define debug_stream somewhere global, though.

If you are concerned about the overhead of your debugger then you can write a very simple code to void out your debug messages on compilation. This is what I use for my c++ programs.
#include <iostream>
#define DEBUGGING // Define this in your config.h or not.
#ifdef DEBUGGING
/*
* replace std::cout with your stream , you don't need to
* worry about the context since macros are simply search
* and replace on compilation.
*/
#define LOG_START std::cout <<
#define LOG_REDIR <<
#define LOG_END << std::endl;
#else
#define LOG_START if(0){(void)
#define LOG_REDIR ;(void)
#define LOG_END ;}
#endif // DEBUGGING
int main(){
LOG_START "This is a log message " LOG_REDIR "Still a log message." LOG_END;
return 0;
}
Now when making your project , check if the user wants to disable the logging , if so , just undefine the DEBUGGING macro or whatever macro you choose to check for.
Now your code will be optimized by the compiler , Because when anything is voided , it will not be included in the resulting binary(most of the time) , making the binary production ready.

I needed a null stream that was of type ostream so I did something like this:
struct NullStream: public stringstream {
NullStream(): stringstream() {}
};
template<typename T>
void operator<<(const NullStream&, const T&) {}
Application code:
NullStream ns;
ostream &os = ns;
os << "foo";
The real issue is all the public methods that I inherited but don't care about so I just didn't bother overriding them.

Related

Laziness in C++11

Do you know how to perform a lazy evaluation of string, like in this D snippet:
void log(lazy string msg) {
static if (fooBarCondition)
writefln(…) /* something with msg */
}
Actually, the problem might not need laziness at all since the static if. Maybe it’s possible to discard char const* strings when not used? Like, in C++:
void log(char const *msg) {
#ifdef DEBUG
cout << … << endl; /* something with msg */
#else /* nothing at all */
#endif
}
Any idea? Thank you.
#ifdef DEBUG
#define log(msg) do { cout << … << endl; } while(0)
#else
#define log(msg) do { } while(0)
#endif
There are two ways to achieve laziness in C++11: macros and lambda expressions. Both are not "lazy" technically, but what is called "normal evaluation" (as opposed to "eager evaluation"), which mean that an expression might be evaluated any number of times. So if you are translating a program from D (or haskell) to C++ you will have to be careful not to use expressions with side effects (including computation time) in these expressions.
To achieve true laziness, you will have to implement memoizing, which is not that simple.
For simple logging, macros are just fine.
You could mix macros and lambdas to create this effect
you could have a type, lazy
template<class T>
class lazy {
...
}
and then you could have a LAZY wrapper that created one of these using a lambda
#define LAZY(E) my_lazy_type<decltype((E))>([&](){ return E; })
All my_lazy_type needs is a constructor that accepts a std::function, and a an overload of operator() that evaluates and returns this. On each evaluation you can replace the thunk with a thunk that just returns the already computed value and thus it would only get computed once.
edit:
here is an example of what I am talking about. I would like however to point out that this is not a perfect example. it passes around a bunch of stuff by value in side the lazy which may completely defeat the purpose of doing this all in the first place. It uses mutable inside this because I need to be able to memoize the thunk in const cases. This could be improved in a lot of ways but it's a decent proof of concept.
#include <iostream>
#include <functional>
#include <memory>
#include <string>
#define LAZY(E) lazy<decltype((E))>{[&](){ return E; }}
template<class T>
class lazy {
private:
struct wrapper {
std::function<T()> thunk;
wrapper(std::function<T()>&& x)
: thunk(std::move(x)) {}
wrapper(const std::function<T()>& x)
: thunk(x) {}
};
//anytime I see mutable, I fill a bit odd
//this seems to be warented here however
mutable std::shared_ptr<wrapper> thunk_ptr;
public:
lazy(std::function<T()>&& x)
: thunk_ptr(std::make_shared<wrapper>(std::move(x))) {}
T operator()() const {
T val = thunk_ptr->thunk();
thunk_ptr->thunk = [val](){return val;};
return val;
}
};
void log(const lazy<std::string>& msg) {
std::cout << msg() << std::endl;
}
int main() {
std::string hello = "hello";
std::string world = "world";
log(LAZY(hello + ", " + world + "!"));
return 0;
}
While Elazar's answer works, I prefer not to use macros for this (especially not ones with all-lowercase names).
Here is what I would do instead:
template<bool /* = false */>
struct logger_impl {
template<typename T>
static std::ostream & write(std::ostream & stream, T const &) {
return stream;
}
};
template<>
struct logger_impl<true> {
template<typename T>
static std::ostream & write(std::ostream & stream, T const & obj) {
return stream << obj;
}
};
template<typename T>
void log(T const & obj) {
#if defined(NDEBUG)
logger_impl<true>::write(std::cout, obj);
#else
logger_impl<false>::write(std::cout, obj);
#endif
}
Just my 2 cents.

Compile time optimization - removing debug prints from release binaries

It is my very first post, so I would like to welcome with everybody. The problem I have occurred is the code optimization at compilation time, and to be more specific removing debug prints.
Let's imagine that we have native syslog logger and we are wrapping it (without using of macros, it is very important note!) with following code:
enum severity { info_log, debug_log, warning_log, error_log };
template <severity S>
struct flusher {
logger* log_;
flusher(logger* log) : log_(log) {}
flusher(flusher& rhs) : log_(rhs.log_) {}
~flusher() { syslog(S, log_->stream.str()); log_->stream.str(""); }
operator std::ostream& () { return log_->stream; }
};
#ifdef NDEBUG
template <> struct flusher<debug_log> {
flusher(logger*) {}
flusher(flusher&) {}
~flusher() {}
template <typename T> flusher& operator<<(T const&) { return *this; }
};
#endif
struct logger {
std::ostringstream stream;
template <severity T>
flusher<T> operator<<(flusher<T> (*m)(logger&)) { return m(*this); }
};
inline flusher<info_log> info(logger& log) { return flusher<info_log>(&log); }
inline flusher<debug_log> debug(logger& log) { return flusher<debug_log>(&log); }
inline flusher<warning_log> warning(logger& log) { return flusher<warning_log>(&log); }
inline flusher<error_log> error(logger& log) { return flusher<error_log>(&log); }
I thought that the empty implementation of flusher will encourage compiler to remove such useless code, but with both O2 and O3 it is not removed.
Is there any possibility to provoke mentioned behaviour?
Thanks in advance
I have successfully done what you're attempting, although with at least two differences... 1) I wasn't using templates - that might be creating a complexity the compiler is unable to optimize out, and 2) my log use included a macro (see below).
Additionally, you may have already done this, make sure all your "empty" definitions are in the logger's header file (so optimizations are done at compile-time and not postponed to link-time).
// use it like this
my_log << "info: " << 5 << endl;
The release definition looks like this:
#define my_log if(true);else logger
and the debug definition looks like this:
#define my_log if(false);else logger
Note that the compiler optimizes out the logger for all if(true) in release, and uses the logger in debug. Also note the full if/else syntax in both cases avoids funny situations where you have unscoped use, e.g.
if (something)
my_log << "this" << endl;
else
somethingelse();
would cause somethingelse to be the else of my_log without it.
Your current code is not preventing the call to f() and any side effects it may have, only preventing the actual printing. This is why macros are the traditional approach to this problem - they provide an unevaluated context where you can check if the value should be printed before actually printing.
In order to achieve this without macros, some extra indirection is needed e.g. std::function, function pointers etc. As an example, you could provide a wrapper class which contained a std::function, and specialise your stream operators to call the std::function in the default case, and not in the NDEBUG case
Very rough example:
//Wrapper object for holding std::functions without evaluating
template <typename Func>
struct debug_function_t {
debug_function_t(Func & f) : f(f) {}
decltype(f()) operator()() { return f(); }
std::function<Func> f;
};
//Helper function for type deduction
template <typename Func>
debug_function_t<Func> debug_function(Func & f) {
return debug_function_t<Func>(f);
}
struct debug_logger {
template <typename T>
debug_logger & operator<<(T & rhs) {}
template <typename Func> //Doesn't call f(), so it's never evaluated
debug_logger & operator<<(debug_function_t<Func> f) { }
};
Then in your client code
int f(){ std::cout << "f()\n"; }
debug_logger log;
log << debug_function(f);
So, following the comment's code:
inline int f()
{
std::cout << 1;
return 1;
}
needs to be made into:
inline int f()
{
#ifndef NDEBUG
std::cout << 1;
#endif
return 1;
}
or something like this:
#ifndef NDEBUG
static const int debug_enable = 1;
#else
static const int debug_enable = 0;
#endif
inline int f()
{
if (debug_enable)
{
std::cout << 1;
}
return 1;
}
You need to tell the compiler somehow that this code isn't needed.
The technique I've used for a few games requires the debug printing to be a function rather than a general expression. E.g.:
debug_print("this is an error string: %s", function_that_generates_error_string());
In release mode, the definition of debug_print is:
#define debug_print sizeof
That removes debug_print and any expression passed to it from the executable. It still has to be passed valid expressions, but they are not evaluated at runtime.

C++ - Best way to create a virtual function to print debug messages [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
pure virtual function and abstract class
I have a class and I want to create a virtual function that will be used to print debug information. Any class that inherits this class will have to implement this virtual function. This way different classes could print the debug messages to different output devices such as std::cout, labels, files etc.
The base class won't be aware of the messages destination. But I don't know the best way to do this. I'm thinking of using something like printf() which can print an arbitrary number of parameters. But I don't know what that would be accomplished. Any ideas?
There is a disadvantage to the approach that you propose. Every derived class will have to implement a printf like facility themselves. That doesn't seem like a very productive activity, and it would make the base class very annoying to use.
It may be less burdensome, code wise, to have the base class require the derived classes provide a debug ostream. Or, you could default to cerr.
class Base {
protected:
virtual std::ostream & debug_stream () const { return std::cerr; }
//...
};
Then, an external user of Base can poke info into the debug_stream.
If you insist on printf style syntax, the interface could return a FILE * instead:
class Base {
protected:
virtual FILE * debug_file () const { return stderr; }
//...
};
So, for example, a derived class could do this:
class Derived : public Base {
static std::ofstream dbgstream;
std::ostream & debug_stream () const { return dbgstream; }
//...
};
std::ofstream Derived::dbgstream("/tmp/derived.dbg");
Then if one has proper access to the base class interface,
void foo (Base *b) {
//...do something with b
b->debug_stream()
<< __FILE__ << ":" << __LINE__ << " foo did something"
<< std::endl;
//...
}
I would do something like this:
class Base
{
protected:
virtual int doDebug(const std::string& Msg) const = 0;
public:
int Debug(const char* MsgFmt, ...) const;
};
int Base::Debug(const char* MsgFmt, ...) const
{
std::string sMsg;
va_list args;
va_start(args, MsgFmt);
int len = vsnprintf(NULL, 0, MsgFmt, args);
if (len > 0)
{
sMsg.resize(len);
vsnprintf(&sMsg[0], len + 1, MsgFmt, args);
}
va_end(args);
return doDebug(sMsg);
}
That way, you still provide the caller with flexible formatting, but the derived classes do not have to worry about that because they are given only pre-formatted text.
I would just do this
class Base
{
virtual int debugfn(const std::string& msg) const = 0;
};
I.e., don't mix the functionality of printf (producing a formatted string and sending it to stdout) with the debugging function. Let it take as its argument a string that is already complete, and let the derived classes decide what to do with it. The int can be an error code if desired, otherwise just return void.
The basic idea here is to use a protected virtual function that takes a string as the error/log/debug-message to be printed / logged. Then, your base class exposes a non-virtual function (or set of functions) to construct the string that will be fed to the protected virtual function. To actually create the string, you can use one of many ways, in the style of printf (with varargs or variadic templates (C++11)), or in the style of standard iostreams. Here is one solution in the latter category:
class BaseDebugOutput {
protected:
virtual void printMessage(const std::string& aMsg) = 0;
private:
std::stringstream temp_stream;
public:
virtual ~BaseDebugOutput() { };
// One << operator for any type.
template <typename T>
BaseDebugOutput& operator<<(const T& value) {
temp_stream << value;
return *this;
};
typedef std::basic_ostream< std::stringstream::char_type,
std::stringstream::traits_type >&
(*ostream_function_ptr)(
std::basic_ostream< std::stringstream::char_type,
std::stringstream::traits_type >&);
// One << operator for things like std::endl.
BaseDebugOutput& operator<<(ostream_function_ptr p) {
if(p == ostream_function_ptr(std::endl)) {
// if the user outputted an end-line, then print the entry:
temp_stream << std::endl;
std::string temp_msg;
std::getline(temp_stream,temp_msg);
// call the protected virtual function:
printMessage(temp_msg);
} else {
temp_stream << p;
};
return *this;
};
};
An example derived class would be:
class CErrDebugOutput : public BaseDebugOutput {
protected:
virtual void printMessage(const std::string& aMsg) {
std::cerr << "Error reported with message: '" << aMsg << "'." << std::endl;
};
};
And the use-case would look like this:
int main() {
BaseDebugOutput* debug_output = new CErrDebugOutput;
(*debug_output) << "The answer is: " << 42 << "!" << std::endl;
delete debug_output;
return;
};
One advantage of the above setup is that you can insert almost anything you want in addition to the error message, such as a time-stamp for example, or just adding the "Error: " string or whatever so that you don't have to repeat that all the time at the points where you issue the messages (call-site).
I might not have understood the question, because the simplest thing that comes to mind has not been offered in all the other answers... If the intention is providing a single entry point for all the hierarchy to print information, then this is the simplest approach:
class base {
public:
virtual std::ostream& print( std::ostream& /*...*/ ) const = 0;
};
std::ostream& operator<<( std::ostream& o, base const & b ) {
return b.print( o );
}
The comment /*...*/ is there because, unlike operator<< the signature is not fixed, so you could pass extra arguments to control the formatting (say, bool single_line, int indent --if !single_line to insert leading spaces, int verbosity to control whether only the public state of the object is to be printed or also auxiliary data...) to produce richer output.
With a single implementation (and a forwarding function) you get printing of the objects to a stream and a way of generating logs with the state of your program for debugging.
If on the other hand what you mean is a solution for derived classes to print debug messages regarding their state at different points in time, then you cannot really do that polymorphically, as the decision to log messages and when should be taken by the derived types. In that case, just pull a logging library and use it. Common logging libraries have very little cost at runtime if the log level is lower than the type of messages (i.e. if you configure to log only warning, the cost of the debug logs (that will not be generated) is very small.

C++ iostream Corruption using stringstream

I'm trying to write a really simple thread-safe logger. Ideally, I wanted it to work just like std::cout, wherein you could just overload the << operator and have everything magically show up in the log. I'm on a Windows machine, so here's the approach I tried:
// Threadsafe logger
class Logger
{
public:
Logger()
{
InitializeCriticalSection(&s);
}
~Logger()
{
DeleteCriticalSection(&s);
}
void Log(std::ostream const& os)
{
EnterCriticalSection(&s);
//std::cout << static_cast<std::stringstream const&>(os).str();
std::cout << os.rdbuf();
LeaveCriticalSection(&s);
}
private:
CRITICAL_SECTION s;
};
Notice that I've tried two approaches to the Log() function. The reason I accept an ostream is because that's what a stringstream seems to produce after the << operator is called. Both variants of the Log() function fail in the same way when I run this code:
#include <iostream>
#include <sstream>
#include <Windows.h>
int main(int argc, char* argv[])
{
Logger logger;
//logger.Log(std::stringstream("Test"));
logger.Log(std::stringstream("Another ") << "test");
std::cin.get();
}
Outputting the first line ("Test") works correctly and displays properly using both variants of the Log function. The second line outputs a mangled output:
testher
which is obviously test written over Another. What am I missing about the way these streams work? I tried making a flush call hoping that would fix things, but it did nothing.
How can I get this attempt at a thread-safe logger working correctly with the streams?
Using variadic templates:
void Log_impl(std::ostream &os) {} // recursion base case
template<typename T,typename... Us>
void Log_impl(std::ostream &os,T &&t,Us &&... us) {
os << std::forward<T>(t);
Log_impl(os,std::forward<Us>(us)...);
}
template<typename... Ts> void Log(Ts &&... ts) {
std::stringstream ss;
Log_impl(ss,std::forward<Ts>(ts)...);
fprintf(stdout,"%s\n",ss.str().c_str()); // thread safe output
}
usage:
Log("Another"," test ",100);
I haven't actually tested this code...
At least in my opinion, this approach to the problem is at least somewhat clumsy to use, since it requires you to create an auxiliary ostream object of some sort, stream data into it, and then pass that to your log. That doesn't seem to fit very closely with what you've said you'd really prefer.
I'm also a bit less than excited about how you've done your thread-locking code. Just for example, if you get an exception during your std::cout << os.rdbuf();, you can exit the scope without leaving the critical section.
I think I'd start with a thin wrapper around a critical section, add an RAII-style class to lock the critical section (and automatically unlock it when it goes out of scope), then use those in implementing the Log class. Further, I'd cheat and have the Log class use a template member function to accept almost any type of output in one fell swoop:
Edit: After some more thought, I've decided to embrace the notion that every problem can be solved with another level of indirection. To do that, I've added an intermediate transaction that encapsulates chaining the output of a number of items into a stringstream, then writing out that result as a thread-safe transaction.
#include <windows.h>
#include <iostream>
#include <sstream>
class crit_sect {
CRITICAL_SECTION cs;
void lock() { EnterCriticalSection(&cs); }
void unlock() { LeaveCriticalSection(&cs); }
friend class lock;
crit_sect(crit_sect const &); /* = delete; */
crit_sect &operator=(crit_sect const &other); /* = delete; */
public:
crit_sect() { InitializeCriticalSection(&cs); }
~crit_sect() { DeleteCriticalSection(&cs); }
};
class lock {
crit_sect &cs;
public:
lock(crit_sect &c) : cs(c) { cs.lock(); }
~lock() { cs.unlock(); }
};
class transaction {
std::ostringstream buffer;
public:
transaction(std::string const &s="") : buffer(s, std::ios::out | std::ios::ate) {}
template <class T>
transaction &operator<<(T const &t) {
buffer << t;
return *this;
}
friend std::ostream &operator<<(std::ostream &os, transaction const &t) {
return os << t.buffer.str();
}
};
class Log {
std::ostream &out;
crit_sect mutex;
public:
Log(std::ostream &sink) : out(sink) { }
template <class T>
void operator<<(T const &t) {
lock l(mutex);
out << t;
}
};
int main() {
Log l(std::cout);
l << "This is a string\n";
l << (transaction("Another ") << "Test");
return 0;
}
Since the log type doesn't support chaining, any attempt at chaining the output without using a transaction will fail (won't compile). Compared to the original, usage is still a bit cleaner though -- the extra parameters needed for the ostringstream ctor are hidden, and the name transaction clarifies what is being done, or rather, accomplished.
The problem isn't with the logger, rather it's with your use of stringstream.
When std::stringstream is initialized, the stream's position indicator is positioned at the beginning of the stream.
Now when you start writing to the string using '<<', you start writing at the position indicator, replacing whatever was there before.
To work around this, you can initialize the stringstream with
std::stringstream("Another ", stringstream::in | stringstream::out | std::stringstream::ate)
(as per http://www.cplusplus.com/reference/iostream/stringstream/stringstream/ )
<< doesn't send the null byte at the end of "test" into the temporary stringstream("Another ") you created, which is why you see "testher".

Printing to nowhere with ostream [duplicate]

This question already has answers here:
Standard no-op output stream
(6 answers)
Closed 2 years ago.
I'd like to send data to nowhere, I mean that I don't want to print data in console nor in file, but I need some std::ostream object. How to do that?
I've used:
std::ostream bitBucket(0);
recently without problems, although it was flagged as having some potential problems if you looked at it from a certain angle (see the link below).
Aside: From what I understand (and I'm not entirely sure of this), that call above eventually ends up calling basic_ios::init(0) and, because that's a NULL pointer being passed in, it sets the stream state, as returned by the rdstate() function, to the badbit value.
This in turn prevents the stream from outputting any more information, instead just tossing it away.
The following program shows it in action:
#include <iostream>
int main (void) {
std::ostream bitBucket(0);
bitBucket << "Hello, there!" << std::endl;
return 0;
}
The page where I got it from also had this as a probably-cleaner solution (slightly modified to remove the duplication of my first solution above):
#include <iostream>
class null_out_buf : public std::streambuf {
public:
virtual std::streamsize xsputn (const char * s, std::streamsize n) {
return n;
}
virtual int overflow (int c) {
return 1;
}
};
class null_out_stream : public std::ostream {
public:
null_out_stream() : std::ostream (&buf) {}
private:
null_out_buf buf;
};
null_out_stream cnul; // My null stream.
int main (void) {
std::cout << std::boolalpha;
//testing nul
std::cout << "Nul stream before: " << cnul.fail() << std::endl;
cnul << "Goodbye World!" << std::endl;
std::cout << "Nul stream after: " << cnul.fail() << std::endl;
}
The simplest solution is just to output to an unopened std::ofstream
(or any other output stream in an error state). This will result in the
stream being permanently in an error state. This could be an advantage
(<< operators will skip the formatting), but if any code that you
can't control checks for errors, and does something particular if they
occur, you'll likely have problems.
Otherwise, it's pretty simple to implement a null stream; the only
streambuf function you really have to override is overflow.
Something like the following should do the trick:
class NulStreambuf : public std::streambuf
{
char dummyBuffer[64];
protected:
virtual int overflow( int c )
{
setp( dummyBuffer, dummyBuffer + sizeof( dummyBuffer ) ) ;
return (c == EOF) ? '\0' : c ;
}
};
(The buffer will avoid some unnecessary virtual function calls. On some
platforms, this makes a significant difference.)
Then create an output stream which uses it:
class NulOStream : public NulStreambuf, public std::ostream
{
public:
NulOStream() : std::ostream( this ) {}
};
(The use of inheritance, rather than containment, ensures that the
streambuf is fully constructed before being passed to the ostream.
This generally isn't necessary in practice, but the standard doesn't
seem to authorize passing a not yet constructed streambuf to the
constructor of ostream.)
Simplest solution: Use a std::stringstream.
#include <sstream>
#include <iostream>
void func(std::ostream& o){
o << "blatest\n";
}
int main(){
std::stringstream black_hole;
func(std::cout);
func(black_hole);
}
The stringstream will contain the output, but if you don't use it, it's the same as if it was never filled.
Since nobody mentioned it, if it's about suppressing std or error output, you can simply close the corresponding file descriptors (e.g. fclose (stdout) or fclose (stderr)).
That will shup up everything, including things like printf or fprintf (stderr, ...)
So you will indeed keep using the usual cout or cerr, but they will be turned into bit buckets.
Some suggestions here: http://bytes.com/topic/c/answers/589209-std-null-stream
A good answer from that site:
Use ordinary std::fstream, open it only for writing to required file
"/dev/null". It should work.
If you really want to create own stream, just derive it from
basic_ostream and simply define your own operator<< to be function
which only returns stream reference. You will have to write dummy
'write' and 'put' method too (and all other methods for output).
#include <streambuf>
#include <ostream>
template <class cT, class traits = std::char_traits<cT> >
class basic_nullbuf: public std::basic_streambuf<cT, traits> {
typename traits::int_type overflow(typename traits::int_type c)
{
return traits::not_eof(c); // indicate success
}
};
template <class cT, class traits = std::char_traits<cT> >
class basic_onullstream: public std::basic_ostream<cT, traits> {
public:
basic_onullstream():
std::basic_ios<cT, traits>(&m_sbuf),
std::basic_ostream<cT, traits>(&m_sbuf)
{
init(&m_sbuf);
}
private:
basic_nullbuf<cT, traits> m_sbuf;
};
typedef basic_onullstream<char> onullstream;
typedef basic_onullstream<wchar_t> wonullstream;
From http://bytes.com/topic/c/answers/428285-null-ostream