Thread: Overloading << and side effects

  1. #1
    Registered User
    Join Date
    Mar 2009
    Posts
    399

    Overloading << and side effects

    I have to overload << for a particular object, and in doing so I use some manipulators from <iomanip> to customize the output. Some of them seem to be permanent though, like std::left and std::right, so what's the best way to customize the output and then reset the stream output format to the way it was?

    I thought about making a temporary copy of the stream before I begin and then assign it back when I'm done, but don't I risk losing the input I have already sent to the stream then (if it's not flushed before it's assigned to)? Also, it's seems a bit excessive to do that and I don't even know if you can assign to an ostream object.

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    You can use the flags() member function to get the format flags, and just before the function returns restore them by using the flags() member function with the fmtflags that was saved as an argument.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    I thought about making a temporary copy of the stream
    The compiler would have stopped you from doing that anyway. Stream objects are not copyable.

    Boost contains a small library that provides RAII objects for saving stream state and automatically restoring it on exit.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. << operator and side effects
    By Memloop in forum C++ Programming
    Replies: 9
    Last Post: 09-11-2009, 09:35 AM
  2. placing two bmp images side by side
    By nina_code in forum C++ Programming
    Replies: 2
    Last Post: 07-14-2009, 11:10 AM
  3. OpenGL example cube is black, white, grey only
    By edwardtisdale in forum Windows Programming
    Replies: 7
    Last Post: 09-22-2007, 02:37 PM
  4. Strange side effects?
    By _Elixia_ in forum C Programming
    Replies: 4
    Last Post: 08-16-2005, 03:25 PM
  5. Side effects
    By Eibro in forum C++ Programming
    Replies: 4
    Last Post: 07-23-2003, 06:26 AM