ROSE  0.11.145.0
Public Member Functions | Protected Attributes | List of all members
FormatRestorer Class Reference

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.

#include <Rose/FormatRestorer.h>

Collaboration diagram for FormatRestorer:
Collaboration graph
[legend]

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
 

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.

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.

Referenced by ~FormatRestorer().


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