Custom output stream that acts like std::cout I wrote a simple output stream object that from the user point of view should act exactly like the classic std::cout. I need it because I want to customize the printing behavior of my program.

Can you review my code? Do you see anything wrong in it?

File Utils.h:

namespace Utils
{
   static std::ostream&amp; Log;
}


File Utils.cpp:

struct MyStream : std::ostream, std::streambuf
{
public:
   MyStream() : std::ostream(this) { }
   std::streambuf::int_type overflow(std::streambuf::int_type c)
   {
      std::cout &lt;&lt; c;
      // My custom operations
      return 0;
   }
};
std::ostream&amp; Utils::Log = MyStream();
Construction

The construction of a MyStream object will proceed like this:


Construct std::ostream part with pointer to not-yet-constructed std::streambuf part.
Construct std::streambuf part.
Construct MyStream part.


Thus, suggestion: Reorder inheritance list like this:

struct MyStream : std::streambuf, std::ostream

override specifier

Nitpick: Add override specifier for overflow() function:

std::streambuf::int_type overflow(std::streambuf::int_type c) override

struct vs class

Another nitpick. I'm noticing that you are using struct instead of class. It is subjective, but I like to distinguish between struct and class like this:


If the resulting object will mostly be used by calling its methods - it's a class.
If the resulting object will mostly be used by accessing its fields - it's a struct.


Thus, for MyStream I would use class instead of struct. But, as I said, it is subjective.