ROSE  0.9.6a
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
FormatRestorer Class Reference

Restores output stream flags to original values. More...

#include <FormatRestorer.h>

Public Member Functions

 FormatRestorer (std::ostream &o)
 Constructor saves output stream flags. More...
 
 ~FormatRestorer ()
 Destructor restores output stream flags. More...
 
void save (std::ostream &o)
 Save current output stream flags. More...
 
void restore ()
 Restore saved flags. More...
 

Protected Attributes

std::ostream & stream
 
std::ios_base::fmtflags fmt
 

Detailed Description

Restores output stream flags to original values.

To make temporary changes to stream flags within a function, first create one of these FormatRestorer objects in the same scope where the temporary changes are being made. When this object goes out of scope the format flags will be restored to their original values.

Example

This code does not work because it assumes that the format was decimal to start with:

void foo(std::ostream &o) {
o <<std::hex <<bar() <<std::dec;
}

This code isn't much better, because it doesn't restore the original format if bar() throws an exception:

void foo(std::ostream &o) {
std::ios_base::fmtflags old_flags = o.flags();
o <<std::hex <<bar();
o.flags(old_flags);
}

This code is overly verbose, and gets worse as you add other return points and exception handling.

void foo(std::ostream &o) {
std::ios_base::fmtflags old_flags = o.flags();
try {
o <<std::hex <<bar();
o.flags(old_flags);
} catch(...) {
o.flags(old_flags);
throw();
}
}

Using the FormatRestorer is cleaner:

void foo(std::ostream &o) {
o <<std::hex <<bar() <<std::dec <<baz();
}

Definition at line 52 of file FormatRestorer.h.

Constructor & Destructor Documentation

FormatRestorer::FormatRestorer ( std::ostream &  o)
inline

Constructor saves output stream flags.

Definition at line 59 of file FormatRestorer.h.

References save().

FormatRestorer::~FormatRestorer ( )
inline

Destructor restores output stream flags.

Definition at line 64 of file FormatRestorer.h.

References restore().

Member Function Documentation

void FormatRestorer::save ( std::ostream &  o)
inline

Save current output stream flags.

Definition at line 69 of file FormatRestorer.h.

References fmt.

Referenced by FormatRestorer().

void FormatRestorer::restore ( )
inline

Restore saved flags.

Flags can be restored as many times as desired.

Definition at line 74 of file FormatRestorer.h.

References fmt, and stream.

Referenced by ~FormatRestorer().

Member Data Documentation

std::ostream& FormatRestorer::stream
protected

Definition at line 54 of file FormatRestorer.h.

Referenced by restore().

std::ios_base::fmtflags FormatRestorer::fmt
protected

Definition at line 55 of file FormatRestorer.h.

Referenced by restore(), and save().


The documentation for this class was generated from the following file: