C Ostream Dev Null

8) Outputs an implementation-defined string as if by.this null-terminated character type string. 9) Behaves as an UnformattedOutputFunction. After constructing and checking the sentry object, checks if sb is a null pointer. C - Overloaded ostream operator in template - i got confused in overloading ostream operator. Dev-C Open Source C & C IDE for Windows Brought to you by: claplace. Summary Files Reviews Support Wiki Mailing Lists Code. I combined three different proposals above and one writing directly to /dev/null (so it involves kernel.) Surprisingly the NullStream that got the most votes performed the worst. Here are results for 100,000,000 writes: a) /dev/null: 30 seconds b) NullStream: 50 seconds c) badbit: 16 seconds (the winner in speed, but cannot test for errors!).

Question

I would like to be able to do:

EDIT: single line solution is crucial since this is for logging purposes. These will be all around the code.

inside foo will print the string to screen or something of the sort.

now since stringstream's operator<< returns ostream&, foo's signature must be:

but how can I convert ostream& to string? (or char*).Different approaches to achieving this use case are welcome as well.

Solution

/dev/null Minecraft

The obvious solution is to use dynamic_cast in foo. But the givencode still won't work. (Your example will compile, but it won't do whatyou think it should.) The expression std::ostringstream() is a temporary, you can't initialize a non-const reference with a temporary,and the first argument of std::operator<<( std::ostream&, char const*)is a non-const reference. (You can call a member function on atemporary. Like std::ostream::operator<<( void const* ). So the codewill compile, but it won't do what you expect.

You can work around this problem, using something like:

std::ostream::flush() returns a non-const reference, so there are nofurther problems. And on a freshly created stream, it is a no-op.Still, I think you'll agree that it isn't the most elegant or intuitivesolution.

What I usually do in such cases is create a wrapper class, whichcontains it's own std::ostringstream, and provides a templatedmemberoperator<< which forwards to the containedstd::ostringstream. Your function foo would take a constreference to this—or what I offen do is have the destructor callfoo directly, so that the client code doesn't even have to worry aboutit; it does something like:

The function log() returns an instance of the wrapper class (but seebelow), and the (final) destructor of this class calls your functionfoo.

There is one slight problem with this. The return value may be copied,and destructed immediately after the copy. Which will wreck havoc withwhat I just explained; in fact, since std::ostringstream isn'tcopyable, it won't even compile. The solution here is to put all of theactual logic, including the instance of std::ostringstream and thedestructor logic calling foo in a separate implementation class, havethe public wrapper have a boost::shared_ptr to it, and forward. Orjust reimplement a bit of the shared pointer logic in your class:

Note that it's easy to extend this to support optional logging; justprovide a constructor for the LogWrapper which sets collector toNULL, and test for this in the operator<<.

EDITED:

One other thing occurs to me: you'll probably want to check whether thedestructor is being called as a result of an exception, and not callfoo in that case. Logically, I'd hope that the only exception youmight get is std::bad_alloc, but there will always be a user whowrites something like:

where the + is a user defined overload which throws.

OTHER TIPS

I would suggest you to use this utility struct:

And use it as:

Demo (with few more example) : http://ideone.com/J995r

Null

More on my blog : Create string on the fly just in one line

C Ostream Dev Null Function

You could use a proxy object for this; this is a bit of framework, but if you want to use this notation in a lot of places then it may be worth it:

This program prints

The idea is to have a little wrapper class which can be implicitely converted into a std::string. The << operator is simply forwarded to the contained std::stringstream. The make_stream() function is strictly speaking not necessary (you could also say StreamProxy(), but I thought it looks a bit nicer.

A couple of options other than the nice proxy solution just presented by Frerich Raabe:

Dev
  • Define a static string stream variable in the header that defines the logging function and use the comma operator in your invocation of the logging function so that this variable is passed rather than the ostream& returned by the stream insertion operator. You can use a logging macro to hide this ugliness. The problem with this solution is that it is a bit on the ugly side, but this is a commonly used approach to logging.

  • Don't use C++ I/O. Use a varargs C-style solution instead. Pass a format string as the first argument, with the remaining arguments being targets for that format string. A problem with this solution is that even if your compiler is smart enough to ensure that printf and its cousins are safe, the compiler probably won't know that this new function is a part of the printf family. Nonetheless, this is also a commonly used approach.

If you don't mind using macros functions, you can make the logging function accept const string&, and use the following macro

And suppose you foo has signature void foo(const string&), you only need the one-liner

This was inspired by James Kanze's answer about static_cast and stringstream.flush. Without the .flush() the above method fails with unexpected output.

Please note that this method should not leak memory, as temporary values, whether in the pointer form or not, are still allocated on the stack and hence destroyed upon return.

Since you're converting to string anyways, why not

This is not possible. As the name ostream implies, it is used for output, for writing to it. You could change the parameter to stringstream&. This class has the method str() which returns a std::string for your use.

EDIT I did not read the issue with operator << returning ostream&. So I guess you cannot simply write your statements within the functions argument list but have to write it before.

You can create a small wrapper around std::ostringstream that will convert back to std::string on use, and have the function take a std::string const &. The first approach to this solution can be found in this answer to a different question.

On top of that, you can add support for manipulators (std::hex) if needed.

Not affiliated with StackOverflow

Get answers to millions of questions and give back by sharing your knowledge with others.

Sign up for an account.

Comments are closed.