Overloading << and side effects

This is a discussion on Overloading << and side effects within the C++ Programming forums, part of the General Programming Boards category; I have to overload << for a particular object, and in doing so I use some manipulators from <iomanip> to ...

  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
    21,409
    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.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    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,893
    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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21