ROSE 0.11.145.147
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();
}
Restores output stream flags to original values.
void restore()
Restore saved flags.

Definition at line 53 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.
 
 ~FormatRestorer ()
 Destructor restores output stream flags.
 
void save (std::ostream &o)
 Save current output stream flags.
 
void restore ()
 Restore saved flags.
 

Protected Attributes

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

Constructor & Destructor Documentation

◆ FormatRestorer()

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

Constructor saves output stream flags.

Definition at line 60 of file FormatRestorer.h.

References save().

◆ ~FormatRestorer()

FormatRestorer::~FormatRestorer ( )
inline

Destructor restores output stream flags.

Definition at line 65 of file FormatRestorer.h.

References restore().

Member Function Documentation

◆ save()

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

Save current output stream flags.

Definition at line 70 of file FormatRestorer.h.

Referenced by FormatRestorer().

◆ restore()

void FormatRestorer::restore ( )
inline

Restore saved flags.

Flags can be restored as many times as desired.

Definition at line 75 of file FormatRestorer.h.

Referenced by ~FormatRestorer().

Member Data Documentation

◆ stream

std::ostream& FormatRestorer::stream
protected

Definition at line 55 of file FormatRestorer.h.

◆ fmt

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

Definition at line 56 of file FormatRestorer.h.


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